<?php
/**
 * 邮件分组控制器类
 * Created by PhpStorm.
 * User: Liujianlin
 * Date: 2017/6/5
 * Time: 16:29
 */

namespace app\controllers\marketing;

use app\components\redis\RedisMarketingEmail;
use app\models\marketing\UserGoods;
use yii;
use app\models\marketing\MailGroup;
use app\models\marketing\MailSubgroup;
use app\models\marketing\UserGroup;
use app\models\marketing\MailSendlist;
use app\components\TemplateMarket;
use app\components\Site;
use yii\data\Pagination;
use app\components\smarty\SmartyNewRenderer;
use app\components\EmailMarket;
use app\models\marketing\MailGroupEmailTypeStatistics;
use app\models\marketing\Category;
use app\models\marketing\GroupSendLog;
use app\models\marketing\GroupOperationLog;
use app\models\marketing\MailTemplate;
use app\models\Elog;
use app\components\SplitSendlist;
class MailGroupController extends \app\base\Controller
{
    /**
     * 默认分页数
     * @var int
     */
    protected $defaultPageSize = 20;
    protected $sendPerMinute = 45000;
    protected $errorCode = [403]; // 这两种类型的状态码则提示发送超限
    
    private $groupId = 0;           // 分组ID
    
    /**
     * 发送邮件内容
     */
    public function actionSendMailContent()
    {
        Yii::$app->params['now_addr'] = "发送管理";
        $data = [];
        $mothod = strtolower(Yii::$app->request->getMethod());
        $site = Yii::$app->request->$mothod('site');
         // 查询网站相关的数据
        $formData = Yii::$app->request->$mothod();
         // 获取当前模版的相关信息
        $TemplateMarket = new TemplateMarket();
        $data =  $TemplateMarket->getTemplateOneById($formData);
        $email = $formData['email'];
        // 组装邮件相关的内容
         // 渲染到smarty模板
         // echo '<pre>';
        // var_dump($data['template_content']);
        // var_dump($data['template_subject']);
        // exit;
        // 查询当前队列当前邮件的相关信息
        $groupModel = new \app\models\marketing\MailGroup();
        $groupInfo = $groupModel->getGroupById($formData['group_id']);
        
        if (isset($groupInfo['site_id'])) {
            $sendListModel = new MailSendlist();
            $sendOne = $sendListModel->getSendListOne($groupInfo['site_id'],$formData['group_id'],$formData['email_id']);
            
            //if (isset($sendOne['send_time']) && $sendOne['send_time']) {
            if (isset($sendOne['last_send']) && $sendOne['last_send']) {
                $weekDay = \yii::$app->bjTime->date('w',$sendOne['last_send']);
               
                $weekDayC = "";
                switch ($weekDay) {
                    case 1: 
                        $weekDayC = "星期一";
                        break;
                    case 2: 
                        $weekDayC = "星期二";
                        break;
                    case 3: 
                        $weekDayC = "星期三";
                        break;
                    case 4: 
                        $weekDayC = "星期四";
                        break;
                    case 5: 
                        $weekDayC = "星期五";
                        break;
                    case 6: 
                        $weekDayC = "星期六";
                        break;
                    case 7: 
                        $weekDayC = "星期日";
                        break;
                    default:
                        $weekDayC = "";
                        break;
                }
                $sendTime = \yii::$app->bjTime->date("Y年m月d日 H:i",$sendOne['last_send'])." (".$weekDayC.")";
            } else {
                $sendTime = "--";
            }
        } else {
             $sendTime = "--";
        }

        // 生成原始邮件
        try {
            $origMail = $this->makeOrigMail($groupInfo, $sendOne, $data['template_subject'], $data['template_content']);
            $data['template_subject'] = $origMail['template_subject'];
            $data['template_content'] = $origMail['template_content'];
        } catch (\Exception $e) {
            $data['template_subject'] = "生成邮件异常";
            $data['template_content'] = $e->getMessage();
        }

        return $this->render("//marketing/mail-group/send-mail-content",
                [
                    'data' => $data,
                    'groupInfo' => $groupInfo,
                    'email' => $email,
                    'sendTime' => $sendTime,
                ]
        );
    }

    /**
     * 生成原始邮件
     * @param $groupInfo                分组信息
     * @param $sendOne                  邮件相关信息
     * @param $mailSubject              邮件模板主题
     * @param $mailContent              邮件模板内容
     * @return mixed
     */
    public function makeOrigMail($groupInfo, $sendOne, $mailSubject, $mailContent)
    {
        $otherVar = "";
        if (1 == $groupInfo['is_auto_group']) {
            $goodsModel = new UserGoods();
            $otherVar = $goodsModel->getOtherVar($groupInfo['site_id'], $sendOne['cart_goods_custom_id']);
        }

        // 生成邮件内容
        // 替换特殊符号
        $emailMarket = new EmailMarket();
        $email = $emailMarket->decryption($sendOne['email']);
        
        // 获取trak_code中utm_campaign参数
        $utmCompaign = '';
        $trackCodeArr = explode('&',$groupInfo['track_code']);
        foreach($trackCodeArr as $trackCode) {
            if(strpos($trackCode,'utm_campaign=') !== false) {
                list($utmCompaignName,$utmCompaign) = explode('=',$trackCode);
                break;
            }
        }
        
        $email_check_code = yii::$app->params['email_check_code'];
        $emailCheckCode = urlencode(urlencode(base64_encode(md5($email_check_code.$email.$utmCompaign))));
        
        $mailContent = str_replace("&quot;", "\"", $mailContent);
        $mailContent = str_replace("&lt;", "<", $mailContent);
        $mailContent = str_replace("&gt;", ">", $mailContent);
        $mailContent = str_replace("&raquo;", ">", $mailContent);
        $mailContent = str_replace("&amp;", "&", $mailContent);
        $mailContent = str_replace('{track_code}', $groupInfo['track_code'], $mailContent);
        $mailContent = str_replace('{$mail_utm_source}','mail_api', $mailContent);  // GA 发送通道设为emarsys
        $mailContent = str_replace('{$name}',$sendOne['firstname'], $mailContent);  // 邮件内容
        $mailContent = str_replace('{$site_id}',$groupInfo['site_id'], $mailContent);  // 邮件内容
        $mailContent = str_replace('{$email}', $email, $mailContent);  // 邮件内容
        $mailContent = str_replace('{$site_user_id}', $sendOne['site_user_id'], $mailContent);  // 网站端的user_id
        $mailContent = str_replace('{$email_encode}', '', $mailContent);  // 邮件内容
        $mailContent = str_replace('$gid',$groupInfo['group_id'], $mailContent);  // 邮件内容
        $mailContent = str_replace('{$code}',$emailCheckCode, $mailContent);  // 邮件内容
       
         // 如果有other_vars则也要替换
        if (!empty($groupInfo['other_vars'])) {
            $otherVars = json_decode($groupInfo['other_vars'],true);
            if (!empty($otherVars)) {   // 替换模板内容和模板标题中的变量
                if (!empty($otherVars['email_title'])) {
                    $mailSubject = str_replace('{email_title}',$otherVars['email_title'] , $mailSubject);
                }
                
                for ($i = 1;$i <= 12; $i++) {
                    if (!empty($otherVars['goods_url'.$i])) {
                        $mailContent = str_replace("{goods_url{$i}}", $otherVars['goods_url'.$i], $mailContent);
                    } else {
                        $mailContent = str_replace("{goods_url{$i}}", '', $mailContent);
                    }
                    if (!empty($otherVars['goods_img'.$i])) {
                        $mailContent = str_replace("{goods_img{$i}}", $otherVars['goods_img'.$i], $mailContent);
                    } else {
                        $mailContent = str_replace("{goods_img{$i}}", '', $mailContent);
                    }
                    if (!empty($otherVars['goods_price'.$i])) {
                        $mailContent = str_replace("{goods_price{$i}}", $otherVars['goods_price'.$i], $mailContent);
                    } else {
                        $mailContent = str_replace("{goods_price{$i}}", '', $mailContent);
                    }
                    if (!empty($otherVars['goods_title'.$i])) {
                        $mailContent = str_replace("{goods_title{$i}}", $otherVars['goods_title'.$i], $mailContent);
                    } else {
                        $mailContent = str_replace("{goods_title{$i}}", '', $mailContent);
                    }
                }
            }
        }
        $data['template_content'] = $mailContent;
       
        $render = new SmartyNewRenderer;
        $render->getDbResource()->setSource($data['template_content']);
        $render->getDbResource()->setMtime(time());
        $render->smarty->clearAllAssign();
        $templateVar = $sendOne;
        $templateVar['track_code'] = $groupInfo['track_code'];
        
        if (!empty($otherVar)) {
            $otherVar = json_decode($otherVar, true);
            if (!empty($otherVar)) {
                $templateVar = array_merge($templateVar, $otherVar);
            }
        }
       
        // $templateVar['nick_name'] = "zs";
        $render->smarty->assign($templateVar);
       
        $data['template_content'] = $render->smarty->fetch("content");
        
        // 生成邮件主题
        $render->getDbResource()->setSource($mailSubject);
        $render->getDbResource()->setMtime(time());
        $render->smarty->clearAllAssign();
        $render->smarty->assign($templateVar);
        $data['template_subject'] = $render->smarty->fetch("subject");
        return $data;
    }
    
    /**
     * 展示当前发送分组的模版信息
     */
    public function actionSendMailTemplate()
    {
        $data = [];
       
        $mothod = strtolower(Yii::$app->request->getMethod());
        $site = Yii::$app->request->$mothod('site');
         // 查询网站相关的数据
        $formData = Yii::$app->request->$mothod();
        if(isset($formData['type']) && $formData['type'] == 'group_conv') {
             Yii::$app->params['now_addr'] = '邮件分组转化统计';
             // 获取当前模版的相关信息
            $TemplateMarket = new TemplateMarket();
            $data =  $TemplateMarket->getTemplateOne($formData);
        } else {
            // 获取当前模版的相关信息
            $TemplateMarket = new TemplateMarket();
            $data =  $TemplateMarket->getTemplateOneById($formData);
        }
        
        $groupInfo = [];
        if(isset($formData['group_id']) && $formData['group_id']) {
            // 查询分组相关信息
            $groupModel = new \app\models\marketing\MailGroup();
            $groupInfo = $groupModel->getGroupById($formData['group_id']);
        }
        
        
        if(isset($formData['contrastive_term']) && $formData['contrastive_term'] == 2) {
            $testGroupTemInfo = $groupModel->getAbTestChildMailGroupById($groupInfo['ab_test_real_id']);
            $data['modify_note'] = $testGroupTemInfo['modify_note'];
        }
        
        return $this->render('//marketing//mail-group/send-mail-template',[
                'data' => $data,
                'groupInfo' => $groupInfo,
                'formData' => $formData
        ]);
    }
    
    /**
     * 发送记录相关
     */
    public function actionSendGroupHistoryList()
    {
        $historyInfo = $this->actionSendGroupList($state=2);
        
        return $this->render('//marketing//mail-group/history-list',[
                'data' => $historyInfo['data'], 
                'site' => $historyInfo['site'],
                'formData' => $historyInfo['formData'],
                'pages' => $historyInfo['pages'],
            ]);
        
    }
    
    /*
     * 添加ab测试发送分组
     */
    public function actionAddAbTestMailGroup()
    {
        $method = yii::$app->request->getMethod();
        $formData = yii::$app->request->$method();
        
        $verify = $this->verifyAddAbUserGroupSendList($formData);
        if (true !== $verify) {
            $this->returnJson(0, $verify);
        }
        
        $data = $formData;
        
        $data['user_define_group'] = isset($data['user_define_group']) ? $data['user_define_group'] : [];
        $data['sys_group'] = isset($data['sys_group']) ? $data['sys_group'] : [];
        $data['exclude_group'] = isset($data['exclude_group']) ? $data['exclude_group'] : [];
//        var_dump($data);exit;
        $groupModel = new MailGroup();
        
        $abTestMailGroupId = intval($data['ab_test_mail_group_id']);
        if($abTestMailGroupId) {
            
            $insertId = $groupModel->updateAbTestGroup($data, $abTestMailGroupId);
        } else {
            $insertId = $groupModel->addAbTestGroup($data);
        }
        
        if($insertId) {
            $this->returnJson(1, "success", ['ab_test_mail_group_id' => $insertId]);
        } else {
            $this->returnJson(0, "添加ab测试数据失败！");
        }
    }
    
    /*
     * 删除ab测试子分组
     */
    public function actionDelTestChildGroup()
    {
        $method = yii::$app->request->getMethod();
        $formData = yii::$app->request->$method();
        $site = yii::$app->request->$method('site');
        $id = yii::$app->request->$method('id');
        if($id) {
            $groupModel = new MailGroup();
            if($data = $groupModel->delAbTestQueue($id)) {
                return $this->redirect(['/marketing/user-group/add-send-queue?site=marketing_email&site_id='.$data['site_id'].'&type=ab_test&parent_test_group_id='.$data['parent_test_group_id']]);
            }
        }
    }
    /*
     * 添加或编辑ab测试子分组
     */
    public function actionAddAbTestQueue()
    {
        $method = yii::$app->request->getMethod();
        $formData = yii::$app->request->$method();
        $site = yii::$app->request->$method('site');
        
        if(!$formData['ab_test_mail_group_id'] || !$formData['site_id'] || !$formData['contrastive_term']) {
            $this->sysMsg('警告', '参数不正确!',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
        }
        
        $TemplateMarket = new MailTemplate();
        $groupModel = new MailGroup();
        $data =  $TemplateMarket->getManualTriggerTemplateDetailBySite($formData['site_id']);
        $templateTypes = [0 => '--请选择模板--'];
        foreach($data as $val) {
            $templateTypes[$val['template_id']] = $val['template_name'];
        }
        if($formData['contrastive_term'] == 1) {
            $view = '//marketing//mail-group/add-ab-test-subject-queue';
        } else if($formData['contrastive_term'] == 2) {
            $view = '//marketing//mail-group/add-ab-test-content-queue';
        }
        
        $templateData = [];
        $curSendUsersTtotalPercent = 0;
        $templateTypeCompain = '';
        
        $testChildData = $groupModel->getAbTestChildMailGroup($formData['ab_test_mail_group_id']);
        if($testChildData){
            $testGroup = $groupModel->getAbTestMailGroup($formData['ab_test_mail_group_id']);
            $templateData = $TemplateMarket->getTemplate(["site_id" => $formData['site_id'], 'template_id' => $testGroup['default_template_id'], "is_del" => 0, "is_use" => 1, 'status' => 1]);
            
            $templateData = array_shift($templateData);
            if($templateData) {
                $templateData['template_subject'] = stripcslashes($templateData['template_subject']);
                $templateData['template_content'] = stripcslashes($templateData['template_content']);
            }
            $templateTypeCompain = isset($templateTypes[$testGroup['default_template_id']]) ? $templateTypes[$testGroup['default_template_id']] : '';
            
            foreach($testChildData as $testChild) {
                $curSendUsersTtotalPercent += $testChild['send_users_percent'];
            }
        }
        
//        var_dump($testChildData);exit;
         return $this->render($view,[
                'data'  => $formData,
                'templateTypes' => $templateTypes, 
                'templateData' => $templateData, 
                'testChildData' => $testChildData, 
                'templateTypeCompain' => $templateTypeCompain, 
                'curSendUsersTtotalPercent' => $curSendUsersTtotalPercent, 
                'site' => $site
            ]);
    }
    /*
     * 添加或编辑ab测试子分组
     */
    public function actionEditAbTestQueue()
    {
        $method = yii::$app->request->getMethod();
        $formData = yii::$app->request->$method();
        $site = yii::$app->request->$method('site');
        $id = yii::$app->request->$method('id');
        
        if(!$id) {
            $this->sysMsg('警告', '参数不正确!',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
        }
        
        
        $groupModel = new MailGroup();
        
        $formData = $groupModel->getAbTestChildMailGroupById($id);
        
        if(!$formData) {
            $this->sysMsg('警告', '数据不存在!',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
        }
        
        
        $TemplateMarket = new MailTemplate();
        $groupModel = new MailGroup();
        $data =  $TemplateMarket->getManualTriggerTemplateDetailBySite($formData['site_id']);
        $templateTypes = [0 => '--请选择模板--'];
        foreach($data as $val) {
            $templateTypes[$val['template_id']] = $val['template_name'];
        }
        if($formData['contrastive_term'] == 1) {
            $view = '//marketing//mail-group/edit-ab-test-subject-queue';
        } else if($formData['contrastive_term'] == 2) {
            $view = '//marketing//mail-group/edit-ab-test-content-queue';
        }
        
        $templateData = [];
        $templateTypeCompain = '';
        $curSendUsersTtotalPercent = 0;
        
        $templateData = $TemplateMarket->getAbTestTemplateDetailById($formData['site_id'],$formData['template_id']);
        
        $templateData = array_shift($templateData);
        if($templateData) {
            $templateData['template_subject'] = stripcslashes($templateData['template_subject']);
            $templateData['template_content'] = stripcslashes($templateData['template_content']);
        }
        $templateTypeCompain = isset($templateTypes[$templateData['template_id']]) ? $templateTypes[$templateData['template_id']] : '';
        
        $testChildData = $groupModel->getAbTestChildMailGroup($formData['parent_test_group_id']);
        foreach($testChildData as $testChild) {
            if($testChild['id'] != $id) {
                $curSendUsersTtotalPercent += $testChild['send_users_percent'];
            }
        }
        
//        var_dump($testChildData);exit;
         return $this->render($view,[
                'data'  => $formData,
                'templateTypes' => $templateTypes, 
                'templateData' => $templateData, 
                'templateTypeCompain' => $templateTypeCompain,
                'curSendUsersTtotalPercent' => $curSendUsersTtotalPercent, 
                'site' => $site
            ]);
    }
    /*
     * 添加或编辑ab测试子分组
     */
    public function actionDoAddTestContentQueue()
    {
        $method = yii::$app->request->getMethod();
        $formData = yii::$app->request->$method();
        $site = yii::$app->request->$method('site');
        
        if(!$formData['ab_test_mail_group_id']) {
            $this->sysMsg('警告', '参数不正确!',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
        }
        $verify = $this->verifyAddAbTestData($formData);
        if (true !== $verify) {
            $this->sysMsg('警告', $verify,$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
        }
        
        $totalNumPercent = Yii::$app->db->createCommand("select sum(send_users_percent) totalUsers from mail_test_child_group where parent_test_group_id =".$formData['ab_test_mail_group_id'])->queryOne();
        if($totalNumPercent['totalUsers'] + $formData['ab_test_send_users_percent'] > 100) {
            $this->sysMsg('警告', '当前分组所选用户百分比已超100%',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
        }
        $TemplateMarket = new TemplateMarket();
        $groupModel = new MailGroup();
        
        $addRes = $TemplateMarket->addTestTemplate($formData);
        if($addRes['template_id']) {
            $addTestChildId = $groupModel->addAbTestQueue($formData, $addRes['template_id']);
            Yii::$app->db->createCommand("update mail_test_group set default_template_id = ".$formData['template_id']." where id = ".$formData['ab_test_mail_group_id'])->execute();
            
            return $this->redirect(['/marketing/user-group/add-send-queue?site=marketing_email&site_id='.$formData['site_id'].'&type=ab_test&parent_test_group_id='.$formData['ab_test_mail_group_id']]);
            
        }
    }
    /*
     * 添加或编辑ab测试子分组
     */
    public function actionDoEditTestContentQueue()
    {
        $method = yii::$app->request->getMethod();
        $formData = yii::$app->request->$method();
        $site = yii::$app->request->$method('site');
        
        if(!$formData['ab_test_mail_group_id']) {
            $this->sysMsg('警告', '参数不正确!',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
        }
        $verify = $this->verifyAddAbTestData($formData);
        if (true !== $verify) {
            $this->sysMsg('警告', $verify,$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
        }
        $totalNumPercent = Yii::$app->db->createCommand("select sum(send_users_percent) totalUsers from mail_test_child_group where parent_test_group_id =".$formData['ab_test_mail_group_id']." and id != ".$formData['ab_test_child_group_id'])->queryOne();
        if($totalNumPercent['totalUsers'] + $formData['ab_test_send_users_percent'] > 100) {
            $this->sysMsg('警告', '当前分组所选用户百分比已超100%',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
        }
        $TemplateMarket = new TemplateMarket();
        $groupModel = new MailGroup();
        $testData = $groupModel->getAbTestChildMailGroupById($formData['ab_test_child_group_id']);
        
        if($TemplateMarket->editTestTemplate($formData,$testData['template_id'])) {
            $addTestChildId = $groupModel->updateAbTestQueue($formData);
            
            return $this->redirect(['/marketing/user-group/add-send-queue?site=marketing_email&site_id='.$formData['site_id'].'&type=ab_test&parent_test_group_id='.$formData['ab_test_mail_group_id']]);
            
        }
    }
    /**
     * 校验发送队列提交的参数
     * @param $formData
     * @return bool|string
     */
    private function verifyAddAbTestData($formData)
    {
        if (!isset($formData['ab_test_child_user_group_name'])) {
            return "没有分组名称";
        }
        if (!isset($formData['ab_test_send_users_percent']) || !intval($formData['ab_test_send_users_percent'])) {
            return "没有发送用户";
        }
        if (!isset($formData['site_id'])) {
            return "没有网站ID";
        }
        if (!isset($formData['template_id'])) {
            return "请选择模板";
        }
        
        return true;
    }
    
    /**
     * 发送分组列表页面
     */
    public function actionSendGroupList($state=0)
    {
        yii::$app->db->enableSlaves = false;        // 禁用从库查询，从主库查询数据。防止生成子分组时主从不同步
        $data = [];
        $siteInfo = [];
        $defaultPageSize = 20;
        $mothod = strtolower(Yii::$app->request->getMethod());
        $site = Yii::$app->request->$mothod('site');
        
        // 查询网站相关的数据
        $formData = Yii::$app->request->$mothod();
        // 当前用户所有有权限的站点
        $siteInfoTmp = Yii::$app->authority->getMarketEmailAccessSite();
        $siteInfo[0] = '全部';
        if (isset($siteInfoTmp) && is_array($siteInfoTmp)) {
            foreach ($siteInfoTmp as $siteInfoTmpK => $iteInfoTmpV) {
                $siteInfo[$iteInfoTmpV['site_id']] = $iteInfoTmpV['name'];
            }
        }
        if (sizeof($siteInfo) < 2) {
            exit('你好，你没有任何网站的相关权限');
        }
        
         
        $formData['siteInfo'] = $siteInfo;
        
        // 发送方式
        if (empty($formData['sendtype'])) {
            $formData['sendtype'] = -1;
        }
        
        // 默认的时间数据
        if (!empty($formData['reservation_time'])){
            $reservationTimeArr = explode(' - ',$formData['reservation_time']);
            $formData['startTime'] = $reservationTimeArr[0];
            $formData['endTime'] = $reservationTimeArr[1];
        }
        
        // 分组类型相关 
        if (empty($formData['group_auto_test'])) {
            $formData['group_auto_test'] = [1,2,3]; // 默认勾选三个分组
        }
        
        // 当前时间 
        $curTime = \yii::$app->bjTime->time();
        $timeYearMonthStart = \yii::$app->bjTime->date('Y-m-d',$curTime-30*24*60*60);
        $timeYearMonthCurrent = \yii::$app->bjTime->date('Y-m-d',$curTime);
        $formData['startTime'] = !empty($formData['startTime']) ? $formData['startTime'] : $timeYearMonthStart;
        $formData['endTime'] = !empty($formData['endTime']) ? $formData['endTime'] : $timeYearMonthCurrent;
        // 当前搜索哪个网站的用户信息
        $formData['site_id'] = isset($formData['site_id']) ? $formData['site_id'] : array_keys($siteInfo)[0];
        
        // 判断有没有当前网站的相关权限
        if ($formData['site_id']) {
            $flag = Yii::$app->authority->judgeMarketEmailHaveSite($formData['site_id']);
            if (!$flag) {
                 $this->sysMsg('警告', '你的账号没有权限!',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
            }
        } 
        
        // 当前分组状态
        $formData['state'] = isset($formData['state']) ? intval($formData['state']) : -1;
        if ($state) {
            $formData['state'] = $state;
        }
        // 分组id或者分组名称
        $formData['group_info'] = isset($formData['group_info']) ? trim($formData['group_info']) : "";
        // 获取邮件类型
        $TemplateMarket = new TemplateMarket();
         if (!empty($formData['site_id'])) {
            $templateTypeArr = $TemplateMarket->getTemplateType($formData['site_id']);
        } else {
            $templateTypeArr = $TemplateMarket->getTemplateType();
        }
       // $templateTypeArr = $TemplateMarket->getTemplateType();
        $templateTypeArrInfo[0] = "全部";
        if (isset($templateTypeArr) && is_array($templateTypeArr)) {
            foreach ($templateTypeArr as $templateTypeArrK => $templateTypeArrV) {
                $templateTypeArrInfo[$templateTypeArrV['id']] = $templateTypeArrV['template_type_name']; 
            } 
            $formData['tempType'] = $templateTypeArrInfo;
        }
        $formData['temp_type_id'] = isset($formData['temp_type_id']) ? intval($formData['temp_type_id']) : 0;
        
        // 分页参数相关
        $page = Yii::$app->request->$mothod('page') ? Yii::$app->request->$mothod('page') : 1;
        $pageSize = Yii::$app->request->$mothod('pagesize') ? Yii::$app->request->$mothod('pagesize') : $defaultPageSize;
        $formData['page'] = $page;
        $formData['pageSize'] = $pageSize;
        
        // 获取分组信息
        $groupModel = new \app\models\marketing\MailGroup();
        $groupInfo = $groupModel->getGroupList($formData);
        
        // 获取当前查询的所有分组id
        $allgroupIdArr = $parentTestGroupId = $testGroupInfos = [];
        $allgroupIdStr = $parentTestGroupIdStr = "";
        
        // 保存每个分组的
        $allGroupInfoStat = [];
        $allGroupInfoStatDeal = [];
        foreach ($groupInfo['groupList'] as $groupListK => $groupListV) {
            $allgroupIdArr[] = $groupListV['group_id'];
            if($groupListV['is_ab_test'] == 1 && $groupListV['ab_test_parent_id'] == 0) {
                $parentTestGroupId[] = $groupListV['group_id'];
            }
        }
        
        $parentTestGroupIdStr = join(',',$parentTestGroupId);
        
        if($parentTestGroupIdStr) {
            $testGroupInfos = $groupModel->getTestChildsGroupList($parentTestGroupIdStr);
            $testGroupTemInfos = $groupModel->getAllTemplateInfoByTestParentGroups($parentTestGroupId);
            
            $testParentGroups = $testParentGroupArr = $abTestGroups = [];
            foreach($testGroupTemInfos as $testGroupTemInfo) {
                $testParentGroups[] = $testGroupTemInfo['parent_test_group_id'];
            }
            $testParentGroups = array_unique($testParentGroups);
            if($testParentGroups) {
                $testParentGroupInfos = $groupModel->getParentTestGroups($testParentGroups);
                foreach($testParentGroupInfos as $testParentGroupInfo) {
                    $testParentGroupArr[$testParentGroupInfo['id']] = $testParentGroupInfo['contrastive_term']; 
                }
            }
            foreach($testGroupTemInfos as $testGroupTemInfo) {
                $abTestGroups[$testGroupTemInfo['group_id']] = $testGroupTemInfo;
                if(isset($testParentGroupArr[$testGroupTemInfo['parent_test_group_id']])) {
                    $abTestGroups[$testGroupTemInfo['group_id']]['contrastive_term'] = $testParentGroupArr[$testGroupTemInfo['parent_test_group_id']];
                }
            }
            foreach($testGroupInfos as $testGroupInfo) {
                $allgroupIdArr[] = $testGroupInfo['group_id'];
            }
            
        }
        $allgroupIdStr = join(',',$allgroupIdArr);
      
        if ($allgroupIdStr) {
            // 查询当前这些分组的统计信息数量和总的发送数量（打开数，点击数，发送成功数，失败数，总发送数）
            $allGroupInfoStatSql = " select * from mail_group_email_type_statistics where gid in ({$allgroupIdStr})"; 
           
            $allGroupInfoStat = Yii::$app->db->createCommand($allGroupInfoStatSql)->queryAll();
            
            if ($allGroupInfoStat) { // 处理相关信息
                foreach ($allGroupInfoStat as $allGroupInfoStatK => $allGroupInfoStatV) {
                    $allGroupInfoStatDeal[$allGroupInfoStatV['gid']][$allGroupInfoStatV['email_type']] = $allGroupInfoStatV;
                }
            }
        }
        
        $channelArr = [2 => 'emarsys', 4 => 'cheet', 6 => 'emarsys_new', 5 => 'benchmark', 9 => 'webpower'];
        $emailMarket = new EmailMarket();
        
        $groupInfo['groupList'] = array_merge($groupInfo['groupList'], $testGroupInfos);
        $returnData = [];
        
        // 分组信息数据处理
        foreach ($groupInfo['groupList'] as $groupListK => $groupListV) {
            
            // 添加队列时间
            $groupInfo['groupList'][$groupListK]['add_date'] = \yii::$app->bjTime->date("Y-m-d H:i:s",$groupListV['add_date']);
            
            // 开始发送时间
            if ($groupListV['start_time']) {
                $groupInfo['groupList'][$groupListK]['start_time'] = \yii::$app->bjTime->date("Y-m-d H:i:s",$groupListV['start_time']);
            } else {
                $groupInfo['groupList'][$groupListK]['start_time'] = '--';
            }
            
            // 最后一次发送时间
            if ($groupListV['group_last_send']) {
                $groupInfo['groupList'][$groupListK]['group_last_send'] = \yii::$app->bjTime->date("Y-m-d H:i:s",$groupListV['group_last_send']);
            } else {
                $groupInfo['groupList'][$groupListK]['group_last_send'] = '--';
            }
            
            // 成功送达率
            if ($groupListV['channel_id'] == 2 || $groupListV['channel_id'] == 6 || $groupListV['channel_id'] == 5  || $groupListV['channel_id'] == 9) {
                $groupListV['send_status_ok_count'] = $groupListV['send_ok_count'] - $groupListV['send_status_fail_count'];
                $groupInfo['groupList'][$groupListK]['send_status_ok_count'] = $groupListV['send_status_ok_count'];
            }
            
            if(empty($groupListV['total_count']))
            {
                $groupInfo['groupList'][$groupListK]['send_status_ok_rate'] =0;
            }else {
                $groupInfo['groupList'][$groupListK]['send_status_ok_rate'] = number_format( $groupListV['send_status_ok_count'] / $groupListV['total_count'] , 4)*100;
            }
           
            // 成功送达率详情
            // $groupInfo['groupList'][$groupListK]['stat']['all_send'] =  
            
            // 打开率点击率相关
            if ($groupListV['send_status_ok_count']) {
                $groupInfo['groupList'][$groupListK]['all_open_rate'] =  number_format($groupListV['open_count'] / $groupListV['send_status_ok_count'],4) * 100;// 总打开率相关数据后面统计
                $groupInfo['groupList'][$groupListK]['click_link_rate'] =  number_format($groupListV['click_link_count'] / $groupListV['send_status_ok_count'],4) * 100;// 总点击率相关数据后面统计
               
            } else {
                $groupInfo['groupList'][$groupListK]['all_open_rate'] = 0;
                $groupInfo['groupList'][$groupListK]['click_link_rate'] = 0;
            }
            //点击转化率
            if($groupListV['open_count']) {
                $groupInfo['groupList'][$groupListK]['click_open_rate'] =  number_format($groupListV['click_link_count'] / $groupListV['open_count'],4) * 100;// 总点击转化率相关数据后面统计
            } else {
                $groupInfo['groupList'][$groupListK]['click_open_rate'] = 0;
            }
            
            // 添加通道名称列
            $groupInfo['groupList'][$groupListK]['channel_name'] = isset($channelArr[$groupListV['channel_id']]) ? $channelArr[$groupListV['channel_id']] : '';
             
            // 发送方式
            if ($groupListV['send_mode'] == 2) {
                $groupInfo['groupList'][$groupListK]['sendtype'] = '推送';
            } else { // 分天发送
                if ($groupListV['send_type'] == 0) {
                    $groupInfo['groupList'][$groupListK]['sendtype'] = '7天发';
                } else {
                    $groupInfo['groupList'][$groupListK]['sendtype'] = $groupListV['send_type'].'天发';
                }
            }
            
            //网站
            $groupInfo['groupList'][$groupListK]['site_name'] = $siteInfo[$groupListV['site_id']];
            
          
            /* 统计信息相关 ----------start---*/
            $groupInfo['groupList'][$groupListK]['stat'] = [];

            if (isset($allGroupInfoStatDeal) && isset($allGroupInfoStatDeal[$groupListV['group_id']])) {
                $groupInfo['groupList'][$groupListK]['stat']['send_success'] = ""; // 成功送达率提示信息 
                $groupInfo['groupList'][$groupListK]['stat']['open'] = ""; // 打开率提示信息 
                $groupInfo['groupList'][$groupListK]['stat']['click'] = ""; // 点击率提示信息 
                $groupInfo['groupList'][$groupListK]['stat']['click_open'] = ""; // 点击转化率提示信息 
                foreach ($allGroupInfoStatDeal[$groupListV['group_id']] as $allGroupInfoStatDealV) {
                    
                    
                    $emailTypeName =  $emailMarket->getEmailTypeName($allGroupInfoStatDealV['email_type']);
                    
                    $sendSuccessTemp = 0;
                    if ($groupListV['channel_id'] == 2 || $groupListV['channel_id'] == 6 || $groupListV['channel_id'] == 5 || $groupListV['channel_id'] == 9) { // 如果是emarsys通道或者benchmark通道则送达率为 成功送达率=（发送总数-硬弹-软弹）/发送数*100%即成功送达率=（发送总数-send_fail）/发送数*100%
                        $sendSuccessTemp = $allGroupInfoStatDealV['sent'] - $allGroupInfoStatDealV['send_fail'];
                        if ($sendSuccessTemp < 0) {
                            $sendSuccessTemp = 0;
                        }
                        $sendSuccessRate = $allGroupInfoStatDealV['sent'] == 0 ? 0: number_format($sendSuccessTemp / $allGroupInfoStatDealV['sent'],4)*100;  //成功送达相关
                        $groupInfo['groupList'][$groupListK]['stat']['send_success'] .= '&#13;'.$emailTypeName.":". $sendSuccessTemp.'/'.$allGroupInfoStatDealV['sent']." " . $sendSuccessRate ."%";
                    } elseif ($groupListV['channel_id'] == 4) { // 如果是emarsys通道则送达率为 成功送达率=（send_success）/ 发送数*100%
                        $sendSuccessTemp = $allGroupInfoStatDealV['send_success'];
                        if ($sendSuccessTemp < 0) {
                            $sendSuccessTemp = 0;
                        }
                        $sendSuccessRate = $allGroupInfoStatDealV['sent'] == 0 ? 0: number_format($sendSuccessTemp / $allGroupInfoStatDealV['sent'],4)*100;  //成功送达相关
                        $groupInfo['groupList'][$groupListK]['stat']['send_success'] .= '&#13;'.$emailTypeName.":". $sendSuccessTemp.'/'.$allGroupInfoStatDealV['sent']." " . $sendSuccessRate ."%";
                    }
                    $groupInfo['groupList'][$groupListK]['stat']['send_success'] = trim($groupInfo['groupList'][$groupListK]['stat']['send_success'],'&#13;');
                    
                    // 邮件打开率
                    $openRate = $sendSuccessTemp <= 0 ? 0: number_format($allGroupInfoStatDealV['open'] / $sendSuccessTemp,4)*100; // 邮件打开相关
                    $groupInfo['groupList'][$groupListK]['stat']['open'] .= '&#13;'.$emailTypeName.":". $allGroupInfoStatDealV['open'].'/'.$sendSuccessTemp." " . $openRate ."%"; 
                    $groupInfo['groupList'][$groupListK]['stat']['open'] = trim($groupInfo['groupList'][$groupListK]['stat']['open'],'&#13;');
                     
                    // 邮件点击率
                    $clickRate = $sendSuccessTemp <= 0 ? 0: number_format($allGroupInfoStatDealV['click_nums'] / $sendSuccessTemp,4)*100; // 邮件点击相关
                    $groupInfo['groupList'][$groupListK]['stat']['click'] .= '&#13;'.$emailTypeName.":". $allGroupInfoStatDealV['click_nums'].'/' . $sendSuccessTemp ." " . $clickRate ."%"; 
                    $groupInfo['groupList'][$groupListK]['stat']['click'] = trim($groupInfo['groupList'][$groupListK]['stat']['click'],'&#13;');
                    
                    //邮件点击转化率
                    $clickOpenRate = $allGroupInfoStatDealV['open'] <= 0 ? 0 : number_format($allGroupInfoStatDealV['click_nums'] / $allGroupInfoStatDealV['open'],4)*100;
                    $groupInfo['groupList'][$groupListK]['stat']['click_open'] .= '&#13;'.$emailTypeName.":". $allGroupInfoStatDealV['click_nums'].'/' . $allGroupInfoStatDealV['open'] ." " . $clickOpenRate ."%"; 
                    $groupInfo['groupList'][$groupListK]['stat']['click_open'] = trim($groupInfo['groupList'][$groupListK]['stat']['click_open'],'&#13;');
                    
                }
            } else {
                $groupInfo['groupList'][$groupListK]['stat']['send_success'] = ""; // 成功送达率提示信息 
                $groupInfo['groupList'][$groupListK]['stat']['open'] = ""; // 打开率提示信息 
                $groupInfo['groupList'][$groupListK]['stat']['click'] = ""; // 点击率提示信息 
                $groupInfo['groupList'][$groupListK]['stat']['click_open'] = ""; // 点击转化率提示信息 
                $emailMarketTypeAll = $emailMarket->getAllEmailTypeInfo();
                foreach ($emailMarketTypeAll as $emailMarketTypeAllK => $emailMarketTypeAllV) {
                    $groupInfo['groupList'][$groupListK]['stat']['send_success'] .= '&#13;'.$emailMarketTypeAllV['mail_name'].":0/0 0%";
                    $groupInfo['groupList'][$groupListK]['stat']['open'] .= '&#13;'.$emailMarketTypeAllV['mail_name'].":0/0 0%";
                    $groupInfo['groupList'][$groupListK]['stat']['click'] .= '&#13;'.$emailMarketTypeAllV['mail_name'].":0/0 0%";
                    $groupInfo['groupList'][$groupListK]['stat']['click_open'] .= '&#13;'.$emailMarketTypeAllV['mail_name'].":0/0 0%";
                }
                   
            } 
            /* 统计信息相关 ----------end---*/
            // 模版标题相关
            $groupInfo['groupList'][$groupListK]['template_subject_brief'] = substr($groupListV['template_subject'],0,45);

            // 当前状态相关
            if ($groupListV['state'] == 0 && $groupListV['boot_time'] > 0) { // 暂停
                $groupInfo['groupList'][$groupListK]['curState'] = '暂停'; 
            } elseif ($groupListV['state'] == 0 && $groupListV['boot_time'] == 0) {
                $groupInfo['groupList'][$groupListK]['curState'] = '未发送';
            } elseif ($groupListV['state'] == 1 && $groupListV['group_last_send'] == 0) {
                $groupInfo['groupList'][$groupListK]['curState'] = '未发送';
            } elseif ($groupListV['state'] == 1 && $groupListV['group_last_send'] > 0) { // 发送中
                $groupInfo['groupList'][$groupListK]['curState'] = '发送中'; 
            } elseif ($groupListV['state'] == 1 && $groupListV['start_time'] > $curTime) { // 发送中
                $groupInfo['groupList'][$groupListK]['curState'] = '启动'; 
            } elseif ($groupListV['state'] == 2) {
                $groupInfo['groupList'][$groupListK]['curState'] = '已发送'; 
            }
            
            // 是否超限相关
            if (!empty($groupInfo['groupList'][$groupListK]['error_code']) && in_array($groupInfo['groupList'][$groupListK]['error_code'],$this->errorCode)) {
                $groupInfo['groupList'][$groupListK]['is_overrun'] = 1;
            }
            
            // 是否为异常分组(未发送完且状态不是已发送或者未发送)
            if(($groupInfo['groupList'][$groupListK]['is_send_exception'] == 1 && $groupInfo['groupList'][$groupListK]['state'] != 2) || ($groupInfo['groupList'][$groupListK]['is_send_exception'] == 2 && $groupInfo['groupList'][$groupListK]['group_last_send'] == 0)) {
                $groupInfo['groupList'][$groupListK]['is_exception'] = 1;
            }
            
            if($groupListV['is_ab_test'] == 1 && $groupListV['ab_test_parent_id'] > 1) {
                
                $groupInfo['groupList'][$groupListK]['ab_test_info'] = isset($abTestGroups[$groupListV['group_id']]) ? $abTestGroups[$groupListV['group_id']] : [];
                $returnData[$groupListV['ab_test_parent_id']]['child'][] = $groupInfo['groupList'][$groupListK];
                
                
            } else {
                $returnData[$groupListV['group_id']] = $groupInfo['groupList'][$groupListK];
            }
        }
//                var_dump($returnData);exit;
//        var_dump($returnData);exit;
        $totalCount = $groupInfo['totalCount'];
        
        
        // 分页相关
        $pages = new Pagination(['totalCount' =>$totalCount, 'pageSize' => $pageSize, 'defaultPageSize' => $pageSize]);
        
//        if ($state == 2 ) {
//            return [
//                'data' => $groupInfo['groupList'], 
//                'site' => $site,
//                'formData' => $formData,
//                'pages' => $pages,
//            ];
//        } else {
//            return $this->render('//marketing//mail-group/list',[
//                'data' => $groupInfo['groupList'], 
//                'site' => $site,
//                'formData' => $formData,
//                'pages' => $pages,
//            ]);
//        }
        return $this->render('//marketing//mail-group/list',[
                'data' => $returnData, 
                'site' => $site,
                'formData' => $formData,
                'pages' => $pages,
            ]);
    }

    /**
     * 设置立即发送
     */
    public function actionImmediateSend()
    {
        $method = yii::$app->request->getMethod();
        $groupId = yii::$app->request->$method('group_id');
        $type = yii::$app->request->$method('type');
        $groupModel = new MailGroup();
        
        if(isset($type) && $type == 'ab_test') {
            
            $groupModel->updateGroup($groupId, ["start_time" => time(), "is_fix_time_send" => 0]);
            
            $testGroups = $groupModel->getTestChildsGroupListByGroupId($groupId);
            foreach($testGroups as $testGroup) {
                if (empty($testGroup['group_id'])) {
                    continue;
                }
                //判断当前分组是否为已发送状态，如果是则退出
                $curGroupInfo = $groupModel->getGroupById($testGroup['group_id']); 
                if($curGroupInfo['state'] == MailGroup::STATE_FINISH) {
                    continue;
                }

                $groupModel->updateGroup($testGroup['group_id'], ["start_time" => time(), "is_fix_time_send" => 0]);

                //添加操作日志
                $session = Yii::$app->session;
                $log = array(
                    'user_id'  => $session['admin_info']['id'],
                    'user_name'  => $session['admin_info']['username'],
                    'group_id'  => $testGroup['group_id'],
                    'operation' => '立即发送'
                );
                $logObj = new GroupOperationLog();
                $logObj->addLog($log);
            }
        } else {
        
            if (empty($groupId)) {
                $this->returnJson(10001, "数据不完整");
            }

            //判断当前分组是否为已发送状态，如果是则退出
            $curGroupInfo = $groupModel->getGroupById($groupId); 
            if($curGroupInfo['state'] == MailGroup::STATE_FINISH) {
                $this->returnJson(10003, "分组id已发送完成！");
            }

            $groupModel->updateGroup($groupId, ["start_time" => time(), "is_fix_time_send" => 0]);

            //添加操作日志
            $session = Yii::$app->session;
            $log = array(
                'user_id'  => $session['admin_info']['id'],
                'user_name'  => $session['admin_info']['username'],
                'group_id'  => $groupId,
                'operation' => '立即发送'
            );
            $logObj = new GroupOperationLog();
            $logObj->addLog($log);
        }
        //添加操作日志结束
        $this->returnJson(0, "success");
    }
    
    /**
     * 显示重发子分组列表
     */
    public function actionResend()
    {
        yii::$app->params['now_addr'] .= '<li>重发子分组</li>';

        $subgroupModel = new MailSubgroup();
        $method = yii::$app->request->getMethod();
        $groupId = yii::$app->request->$method("group_id");
        $subgroupId = yii::$app->request->$method("subgroup_id");
        $state = yii::$app->request->$method("state");
        $page = yii::$app->request->$method("page", 1);
        $pageSize = yii::$app->request->$method("pagesize", $this->defaultPageSize);

        $whereParam = [];
        if (!empty($groupId)) {
            $whereParam['group_id'] = $groupId;
        }
        if (!empty($subgroupId)) {
            $whereParam['subgroup_id'] = $subgroupId;
        }
        if (isset($state) && -1 != $state) {
            $whereParam['state'] = $state;
        }

        $pageParam = ['page' => $page, 'pageSize' => $pageSize];
        $result = $subgroupModel->getSubgroup($whereParam, $pageParam);
        $data = $result['data'];
        $stateArr = [0 => "暂停", 1 => "加入队列中", 2 => "发送完成", 3 => "发送失败", 4 => "重发", 5 => "停止重发",6 => "正在生成缓存数据"];
        foreach ($data as $key => $value) {
            $data[$key]['add_time'] = \yii::$app->bjTime->date('Y-m-d H:i:s', $value['add_time']);
            $data[$key]['state_name'] = $stateArr[$value['state']];
        }
        $pages = new Pagination(['totalCount' => $result['count'], 'pageSize' => $pageSize, 'defaultPageSize' => $pageSize]);
        return $this->render("/marketing/mail-group/resend", [
            'data' => $data,
            'formData' => $whereParam,
            'pages' => $pages
        ]);
    }

    /**
     * 手动重发
     */
    public function actionManualResend()
    {
        $subgroupModel = new MailSubgroup();
        $idArr = yii::$app->request->post("ids");
        if (empty($idArr)) {
            $this->returnJson(10001, "数据不完整：id为空");
        }

        if (!is_array($idArr)) {
            $idArr = [$idArr];
        }

        $trans = Yii::$app->db->beginTransaction();
        try {
            // 更新数据库的状态
            foreach ($idArr as $value) {
                $subgroupModel->updateSubgroupByCondition(["id" => $value], ["state" => MailSubgroup::STATE_START_RETRY]);
            }
            $trans->commit();
            $this->returnJson(0, "success");
        } catch(\Exception $e) {
            $trans->rollBack();
            $this->returnJson(10008, "更新数据失败，请重试");
        }
    }
    
    /**
     * 重新切割
     */
    public function actionManualRecut()
    {
        $subgroupModel = new MailSubgroup();
        $redis = new RedisMarketingEmail();
        $waitSubgroupKey = 'wait_subgroup'; // 待处理子分组健值
        $id = yii::$app->request->post("ids");
        if (empty($id)) {
            $this->returnJson(10001, "数据不完整：id为空");
        }
        $id = $id[0];
        // 查询相关子分组数据重新加入缓存
        $subgroupInfo = $subgroupModel->getCutSubgroupById($id);
        if ($subgroupInfo) {
            $waitSubgroupVal ="wait_subgroup_{$subgroupInfo['group_id']}_{$subgroupInfo['subgroup_id']}_{$subgroupInfo['send_count']}";
            $returnFlag = $redis->rpush($waitSubgroupKey,$waitSubgroupVal); // 往redis中批量插入数据
            if ($returnFlag) {
                $this->returnJson(0, "success");
            } else {
                $this->returnJson(10007, "缓存添加失败");
            }
        } else {
            $this->returnJson(10008, "获取数据失败，请重试");
        }
    }
    /**
     * 停止手动重发
     */
    public function actionStopManualResend()
    {
        $subgroupModel = new MailSubgroup();
        $id = yii::$app->request->post("id");
        if (empty($id)) {
            $this->returnJson(10001, "数据不完整：id为空");
        }

        $trans = Yii::$app->db->beginTransaction();
        try {
            // 更新数据库的状态
            $subgroupModel->updateSubgroupByCondition(["id" => $id], ["state" => MailSubgroup::STATE_STOP_RETRY]);
            $trans->commit();
            $this->returnJson(0, "success");
        } catch(\Exception $e) {
            $this->returnJson(10008, "更新数据失败，请重试");
        }
    }

    /**
     * 分组调整（调整worker、优先级）
     */
    public function actionAdjustGroup()
    {
        $groupModel = new MailGroup();
        $redis = new RedisMarketingEmail();
        $method = yii::$app->request->getMethod();
        $formData = yii::$app->request->$method();
        $groupId = yii::$app->request->$method("group_id");
        $sendState = yii::$app->request->$method("send_state");
        $page = yii::$app->request->$method("page", 1);
        $pageSize = yii::$app->request->$method("pagesize", $this->defaultPageSize);

        $whereParam = [];
        if (!empty($groupId)) {
            $whereParam['group_id'] = $groupId;
        }

        $sendingGroup = $redis->zrangebyscore("main", "-inf", "(10000");    // 获取redis发送中的分组

        $pageParam = ['page' => $page, 'pageSize' => $pageSize];
        if (0 == $sendState) {      // 获取全部分组
            $result = $groupModel->getGroup($whereParam, $pageParam);
            foreach ($result['data'] as $key => $value) {
                $result['data'][$key]['send_state'] = '非发送中';    // 默认状态：非发送中
                if (in_array("group_" . $value['group_id'], $sendingGroup)) {
                    $result['data'][$key]['send_state'] = '发送中';
                }
            }
        } else {    // 获取发送中分组
            $result['count'] = count($sendingGroup);
            $groupIdArr = [];
            $offset = ($pageParam['page']-1)*$pageParam['pageSize'];
            for ($i = $offset; $i < ($offset + $pageSize) && $i < $result['count']; $i++) {
                $groupIdArr[] = str_replace("group_", "", $sendingGroup[$i]);
            }

            $result['data'] = $groupModel->getGroupByIdArr($groupIdArr);
            foreach ($result['data'] as $key => $value) {
                $result['data'][$key]['send_state'] = '发送中';
            }
        }

        $data = $result['data'];
        $pages = new Pagination(['totalCount' => $result['count'], 'pageSize' => $pageSize, 'defaultPageSize' => $pageSize]);
        return $this->render("/marketing/mail-group/adjust-group", [
            'data' => $data,
            'formData' => $formData,
            'pages' => $pages
        ]);
    }

    /**
     * 处理调整分组提交的数据
     */
    public function actionDoAdjustGroup()
    {
        $method = yii::$app->request->getMethod();
        $formData = yii::$app->request->$method();
        if (empty($formData['groupId'])) {
            $this->returnJson(10001, "数据不完整，没有提交分组ID");
        }
        if (!isset($formData['priority'])) {
            $this->returnJson(10001, "数据不完整，没有提交优先级");
        }
        if (!isset($formData['workerNum'])) {
            $this->returnJson(10001, "数据不完整，没有提交worker数");
        }

        // 更新数据库
        $data = ["worker_num" => $formData['workerNum'], "priority" => $formData['priority']];
        $groupModel = new MailGroup();
        $groupModel->updateGroup($formData['groupId'], $data);

        // 更新redis
        $groupDetailKey = "group_detail_" . $formData['groupId'];
        $groupKey = "group_" . $formData['groupId'];
        $retryGroupKey = "retry_group_" . $formData['groupId'];
        $redis = new \app\components\redis\RedisMarketingEmail();
        if ($redis->exists($groupDetailKey)) {
            $redis->hmset($groupDetailKey, "worker_num", $formData['workerNum'], "priority", $formData['priority']);
        }

        if (null !== $redis->zscore("main", $groupKey)) {
            $redis->zadd("main", [$formData['priority'], $groupKey]);
        }
        if (null !== $redis->zscore("retry_main", $retryGroupKey)) {
            $redis->zadd("retry_main", [$formData['priority'], $retryGroupKey]);
        }

        $this->returnJson(0, "success");
    }

    /**
     * 显示处理进程
     * @return string
     */
    public function actionProcess()
    {
        $redis = new RedisMarketingEmail();
        $processHash = $redis->hgetall("process");
        $processArr = $redis->redisArrToCommonArr($processHash);
        $itemArr = [];

        foreach ($processArr as $key => $value) {
            $process = json_decode($value, true);
            $process['process_name'] = $key;
            $groupId = $process['group_id'] * 1;
            if (!empty($groupId)) {
                $itemArr[$groupId][] = $process;
            }
        }
        ksort($itemArr, SORT_NUMERIC); // 对分组排序
        $data = [];
        foreach ($itemArr as $groupProcess) {
            foreach ($groupProcess as $value) {
                $value['start_time'] = yii::$app->bjTime->date("Y-m-d H:i:s", $value['start_time']);
                $data[] = $value;
            }
        }

        return $this->render("/marketing/mail-group/process", ['data' => $data]);
    }

    /**
     * 添加发送队列
     */
    public function actionAddSendList()
    {
        ini_set('memory_limit', '1024M');
        
        $method = yii::$app->request->getMethod();
        $formData = yii::$app->request->$method();
        if(isset($formData['test_no_send']) && $formData['test_no_send'] == 1) {
            $verify = $this->verifyAddTestNoSendList($formData);
        } else {
            $verify = $this->verifyAddSendList($formData);
        }
        
        if (true !== $verify) {
            exit("添加分组失败：" . $verify);
        }
        
        $data = $formData;
        if(isset($formData['test_no_send']) && $formData['test_no_send'] == 1) {
        } else {
            $data['user_count'] = count($data['user_id']);
        }
        //对emarsys新旧通道进行上线判定
        $isToMax = $this->isToMax($data,2);
        //如果判断结果为true，就给出提示信息
        if($isToMax) {
            exit("已超通道限制，请选其他通道！");
        }
        
        $data['boot_time'] = 0;     // 启动时间
        $data['state'] = MailGroup::STATE_STOP;     // 默认状态为停止发送
        $data['send_type'] = 0;
        if (isset($data['send_type_time'])) {
            $data['send_type'] = $data['send_type_time'];
        }
//        if (is_numeric($data['time_zone'])) {      // 如果是定时发送，那么分组状态为启动状态
//            $data['state'] = MailGroup::STATE_START;
//            $data['boot_time'] = time();
//        }

        $data['start_time'] = 0;
        $data['is_fix_time_send'] = 0;
        if (is_numeric($formData['time_zone']) && !empty($formData['time_zone_clock'])) {
            
            $data['state'] = MailGroup::STATE_START;
            $data['boot_time'] = time();
            
            $newSysTime = new \app\components\NewSysTime($formData['time_zone']);
            $data['start_time'] = $newSysTime->strtotime($formData['time_zone_clock']);
            $data['is_fix_time_send'] = 1;
        }
        $data['track_code'] = "utm_source=mail_api&utm_medium=mail&utm_campaign=" . $formData['utm_campaign'];
        
          // 通过template_pk来获取custom_track_code
//        $selectSql = "select custom_track_code from mail_template where id = ".$data['template_pk'];
//        $customTrackCode = Yii::$app->db->createCommand($selectSql)->queryOne();
//        if (!empty($customTrackCode)  && !empty($customTrackCode['custom_track_code'])) {
//             $data['track_code'] .= '&'.$customTrackCode['custom_track_code'];
//        }
        
        $data['send_per_minute'] = 1000;        // 每次发送数，默认1000
        if (2 == $data['channel_id']) {     // emarsys通道，每次发送数为45000
            $data['send_per_minute'] = $this->sendPerMinute;
        }
        
        if (4 == $data['channel_id']) {     // cheet通道，每次发送数为45000
            $data['send_per_minute'] = $this->sendPerMinute;
        }
        
        if (5 == $data['channel_id']) {     // benchmark通道，每次发送数为45000
            // $data['send_per_minute'] = $this->sendPerMinute;
            $data['send_per_minute'] = 1000;
        }
        
        if (9 == $data['channel_id']) { 
            $data['send_per_minute'] = 100;
        }
		
		$data['is_ab_test'] = 0;
        if(isset($data['type']) && $data['type'] == "ab_test") {
            $data['is_ab_test'] = 1;
            $data['ab_test_parent_id'] = 1;
        }
		
        $groupModel = new MailGroup();
        $sendListModel = new MailSendlist();
        $statModel = new MailGroupEmailTypeStatistics();

        $trans = Yii::$app->db->beginTransaction();
        try {
            $groupId = $groupModel->addGroup($data);
            if(isset($formData['test_no_send']) && $formData['test_no_send'] == 1) {
                $count = $sendListModel->updateSendListByGroupId($data['site_id'], $groupId, $data['channel_id'],
                    $data['template_pk'], $data['group_id']);
            } else {
                $count = $sendListModel->addSendListByUserId($data['site_id'], $groupId, $data['channel_id'],
                    $data['template_pk'], $data['user_id']);
            }
            if (0 == $count) {
                $groupModel->updateGroupByCondition(['group_id' => $groupId], ['is_del' => 1]);
            } else {
                $groupModel->updateGroupByCondition(['group_id' => $groupId], ['total_count' => $count]);
                $statModel->addMailStatItem($groupId, $data['site_id']);
            }
            $trans->commit();
            
            return $this->redirect(['/marketing/mail-group/send-group-list?site=marketing_email']);
            //echo "添加分组成功, 分组id[{$groupId}].跳转到发送分组页面....";
        } catch (\Exception $e) {
            $trans->rollBack();
            exit("添加分组失败：系统繁忙，请稍后重试");
        }

    }
    
    /**
     * 校验发送队列提交的参数
     * @param $formData
     * @return bool|string
     */
     private function verifyAddTestNoSendList($formData)
    {
        if (!isset($formData['group_name'])) {
            return "没有分组名称";
        }
        if (!isset($formData['utm_campaign'])) {
            return "没有utm_campaign";
        }
        if (!isset($formData['site_id'])) {
            return "没有网站ID";
        }
        if (!isset($formData['template_id']) || !is_numeric($formData['template_pk'])) {
            return "请选择模板";
        }
        if (!isset($formData['send_mode'])) {
            return "请选择发送方式";
        }
        if (1 == $formData['send_mode'] && !isset($formData['send_type_time'])) {
            return "请选择邮件发送的天数";
        }
        if (isset($formData['time_zone'])) {
            if (!isset($formData['time_zone_clock'])) {
                return "请填写所选时区的时间";
            }
        }
        if (empty($formData['channel_id'])) {
            return "请选择通道";
        }
        if (empty($formData['sender'])) {
            return "请提交发送邮箱";
        }
        return true;
    }
    /**
     * 校验发送队列提交的参数
     * @param $formData
     * @return bool|string
     */
    private function verifyAddSendList($formData)
    {
        if (!isset($formData['group_name'])) {
            return "没有分组名称";
        }
        if (!isset($formData['utm_campaign'])) {
            return "没有utm_campaign";
        }
        if (!isset($formData['site_id'])) {
            return "没有网站ID";
        }
        if (!isset($formData['template_id']) || !is_numeric($formData['template_pk'])) {
            return "请选择模板";
        }
        if (!isset($formData['send_mode'])) {
            return "请选择发送方式";
        }
        if (1 == $formData['send_mode'] && !isset($formData['send_type_time'])) {
            return "请选择邮件发送的天数";
        }
        if (isset($formData['time_zone'])) {
            if (!isset($formData['time_zone_clock'])) {
                return "请填写所选时区的时间";
            }
        }
        if (empty($formData['user_id'])) {
            return "用户数据不能为空";
        }
        if (empty($formData['channel_id'])) {
            return "请选择通道";
        }
        if (empty($formData['sender'])) {
            return "请提交发送邮箱";
        }
        return true;
    }
/*
 * 对emarsys新旧通道进行是否达到上线判断
 */
    public function isToMax($data,$tag=1) {
        $emarsysTotalTaskNums = 1200;
        $emarsysReserveTaskNums = 100;
        $emarsysNewTotalTemplateNums = 100;
        $emarsysNewReserveTemplateNums = 8;
        
//        $emarsysTotalTaskNums = 1200;
//        $emarsysReserveTaskNums = 1199;
//        $emarsysNewTotalTemplateNums = 100;
//        $emarsysNewReserveTemplateNums = 99;
        
        $sendLogModel = new GroupSendLog();
        //对emarsys通道进行上线判断(24小时内的发送任务数不能超过1000)
        if($data['channel_id'] == 2) {
            
            //获取emarsys通道往前推24小时内的已发送的任务数
            $usedTaskNums = $sendLogModel->getUsedTaskNums();
            $count = 0;
            //获取要发送的用户数
            if($tag == 1 && !empty($data['select_info'])) {
                /**
                 * $countSql = "select count(*) from {$data['select_info']['tableName']} where {$data['select_info']['whereStr']}";
                 * 统计匹配记录数
                 */
                $countSql = "select SQL_CACHE SQL_CALC_FOUND_ROWS 1 from {$data['select_info']['tableName']} where {$data['select_info']['whereStr']} order by NULL limit 1";
                $countSqlResult = 'SELECT FOUND_ROWS()';
                
                $tmpCount = yii::$app->db->createCommand($countSql)->queryScalar();
                $count = yii::$app->db->createCommand($countSqlResult)->queryScalar();
                
            }
            if($tag == 2 && !empty($data['user_count'])) {
                $count = $data['user_count'];
            }
            if($count > 0 && ceil($count/$this->sendPerMinute) > ($emarsysTotalTaskNums - $emarsysReserveTaskNums - $usedTaskNums)) {
                return true;
            }
            
        }else if($data['channel_id'] == 6) {//对emarsys_new通道进行上线判断（24小时内的发送模板数不能超过100）
            //获取emarsys_new通道往前推24小时内的已发送的分组模板数
            $usedTemplateNums = $sendLogModel->getUsedTemplateNums();
            if($usedTemplateNums > 0 && ($emarsysNewTotalTemplateNums - $emarsysNewReserveTemplateNums - $usedTemplateNums) <= 0) {
                return true;
            }
            
        }
        
        return false;
    }
    /*
     * 检测用户列表添件分组是否达到emarsys通道的上限
     */
    public function actionCheckUsersIsEmarsysMax()
    {
        $method = yii::$app->request->getMethod();
        $formData = yii::$app->request->$method();
        if(isset($formData['test_no_send']) && $formData['test_no_send'] == 1) {
            $verify = $this->verifyAddTestNoSendList($formData);
        } else {
            $verify = $this->verifyAddSendList($formData);
        }
        
        if (true !== $verify) {
            $this->returnJson(0, $verify);
        }
        
        $data = $formData;
        if(isset($formData['test_no_send']) && $formData['test_no_send'] == 1) {
            
        } else {
            $data['user_count'] = count($data['user_id']);
        }
        
        //对emarsys新旧通道进行上线判定
        $isToMax = $this->isToMax($data,2);
        //如果判断结果为true，就给出提示信息
        if($isToMax) {
            $this->returnJson(0, "已超通道限制，请选其他通道！");
        }
        
        $this->returnJson(1, "success");
    }
    /*
     * 检测用户分群添加分组是否达到emarsys通道的上限
     */
    public function actionCheckIsEmarsysMax()
    {
        $method = yii::$app->request->getMethod();
        $formData = yii::$app->request->$method();
        
        $verify = $this->verifyAddUserGroupSendList($formData);
        if (true !== $verify) {
            $this->returnJson(0, $verify);
        }
        $data = $formData;
        $data['user_define_group'] = isset($data['user_define_group']) ? $data['user_define_group'] : [];
        $data['sys_group'] = isset($data['sys_group']) ? $data['sys_group'] : [];
        $data['exclude_group'] = isset($data['exclude_group']) ? $data['exclude_group'] : [];
        $userGroupModel = new UserGroup();
        
        $siteName = Site::getInstance()->getSiteShortNameById($data['site_id']);
       
        $allSelectInfo = [];
        if ($data['site_id'] == 31) {
            $this->returnJson(1, "success");
        } else {
           
            $allSelectInfo = $userGroupModel->makeMergeTempTable($siteName, $data['user_define_group'], $data['sys_group'], $data['exclude_group']);
           
            $data['select_info'] = $allSelectInfo;
            //对emarsys新旧通道进行上线判定
            $isToMax = $this->isToMax($data,2);
            //如果判断结果为true，就给出提示信息
            if($isToMax) {
                $this->returnJson(0, "已超通道限制，请选其他通道！");
            } 
        }
        $this->returnJson(1, "success");
    }
    
    /*
     * 编辑发送分组
     * @author liugang 2018-2-26
     */
    public function actionEditSendGroup()
    {
        $method = yii::$app->request->getMethod();
        $formData = yii::$app->request->$method();
        $groupId = $formData['group_id'] ? intval($formData['group_id']) : 0;
        $site = $formData['site'] ? trim($formData['site']) : '';
        $type = isset($formData['type']) ? trim($formData['type']) : '';
        
        $groupModel = new MailGroup();
        if($groupId) {
            $groupInfo = $groupModel->getGroupById($groupId);
            $data = [];
            $data['send_mode'] = $groupInfo['send_mode'];
            $data['send_type'] = $groupInfo['send_type'];
            $data['group_name'] = $groupInfo['group_name'];
            $data['group_id'] = $groupInfo['group_id'];
            $data['group_last_send'] = $groupInfo['group_last_send'];
            
            return $this->render("//marketing/mail-group/edit-send-group", [
                'data' => $data,
                'site' => $site,
                'type' => $type
            ]);
            
        } else {
            $this->sysMsg('警告', "分组id不存在！",
                [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
        }
        
    }
    
    /*
     * 保存编辑发送分组数据
     * @author liugang 2018-2-26
     */
    public function actionDoEditSendGroup()
    {
        $method = yii::$app->request->getMethod();
        $formData = yii::$app->request->$method();
        $groupId = $formData['group_id'] ? intval($formData['group_id']) : 0;
        $type = $formData['type'];
        $groupModel = new MailGroup();
        $updateData = [];
        if(isset($type) && $type == 'ab_test') {
            
            $curGroupInfo = $groupModel->getGroupById($groupId);
            
            if($curGroupInfo['send_ok_count'] == 0) {
                if(is_numeric($formData['time_zone']) && !empty($formData['time_zone_clock'])) {

                    if($curGroupInfo['state'] != MailGroup::STATE_START) {
                        $updateData['state'] = MailGroup::STATE_START;
                        $updateData['boot_time'] = time();
                    }

                    $newSysTime = new \app\components\NewSysTime($formData['time_zone']);
                    $updateData['start_time'] = $newSysTime->strtotime($formData['time_zone_clock']);
                    $updateData['is_fix_time_send'] = 1;
                }
                if($updateData) {
                    // 将更改数据入库
                    $groupModel->updateGroup($groupId,$updateData);

                }
            }
                        
            $testGroups = $groupModel->getTestChildsGroupListByGroupId($groupId);
            foreach($testGroups as $testGroup) {
                if($testGroup['group_id']) {
                    $curGroupInfo = $groupModel->getGroupById($testGroup['group_id']);
                    $updateData = [];
                    if($curGroupInfo['state'] == 2) {// 当前分组为已发送
                        continue;
                    } else if($curGroupInfo['send_ok_count'] == 0) { // 分组未开始发送


                        if (is_numeric($formData['time_zone']) && !empty($formData['time_zone_clock'])) {

                            if($curGroupInfo['state'] != MailGroup::STATE_START) {
                                $updateData['state'] = MailGroup::STATE_START;
                                $updateData['boot_time'] = time();
                            }

                            $newSysTime = new \app\components\NewSysTime($formData['time_zone']);
                            $updateData['start_time'] = $newSysTime->strtotime($formData['time_zone_clock']);
                            $updateData['is_fix_time_send'] = 1;
                        }

                        if($updateData) {
                            // 将更改数据入库
                            if($groupModel->updateGroup($testGroup['group_id'],$updateData)) {
                                continue;
                            }
                        }


                    }
                }
            }
            $this->returnJson(1, "修改成功");
        } else {
        
        
            if($groupId) {
                $curGroupInfo = $groupModel->getGroupById($groupId);
                $updateData = [];
                if($curGroupInfo['state'] == 2) {// 当前分组为已发送
                    $this->returnJson(0, "修改失败");
                } else if($curGroupInfo['send_ok_count'] == 0) { // 分组未开始发送

                    if($formData['send_mode'] != $curGroupInfo['send_mode'] || $formData['send_type_time'] != $curGroupInfo['send_type']) {
                        $updateData['send_mode'] = $formData['send_mode'];
                        $updateData['send_type'] = $formData['send_type_time'];
                    }

                    if (is_numeric($formData['time_zone']) && !empty($formData['time_zone_clock'])) {

                        if($curGroupInfo['state'] != MailGroup::STATE_START) {
                            $updateData['state'] = MailGroup::STATE_START;
                            $updateData['boot_time'] = time();
                        }

                        $newSysTime = new \app\components\NewSysTime($formData['time_zone']);
                        $updateData['start_time'] = $newSysTime->strtotime($formData['time_zone_clock']);
                        $updateData['is_fix_time_send'] = 1;
                    }

                    if($updateData) {
                        // 将更改数据入库
                        if($groupModel->updateGroup($groupId,$updateData)) {
                            $this->returnJson(1, "修改成功");
                        } else {
                            $this->returnJson(0, "修改失败");
                        }
                    } else {
                        $this->returnJson(1, "修改成功");
                    }
                
                
                } else if($curGroupInfo['send_ok_count'] > 0) { // 分组已开始发送
                    if($formData['send_mode'] != $curGroupInfo['send_mode'] || $formData['send_type_time'] != $curGroupInfo['send_type']) {
                        $updateData['send_mode'] = $formData['send_mode'];
                        $updateData['send_type'] = $formData['send_type_time'];
                    }

                    if($updateData) {
                        if($groupModel->updateGroup($groupId,$updateData)) {
                            $this->returnJson(0, "发送方式修改成功,定时发送修改失败");
                        } else {
                            $this->returnJson(0, "发送方式修改失败,定时发送修改失败");
                        }
                    } else {
                        $this->returnJson(0, "发送方式修改成功,定时发送修改失败");
                    }

                }

            } else {
                $this->returnJson(0, "分组id不存在！");
            }
        }
    }
    
    /**
     * 添加分群的发送队列
     * $importType ='manual' 手动导入，system 系统生成
     */
    public function actionAddUserGroupSendList()
    {
        ini_set('memory_limit', '1024M');
        $importType = 'system';   //系统生成的用户
        if (isset($_REQUEST['importType'])) {
            $importType = $_REQUEST['importType'];
        }
        
        $method = yii::$app->request->getMethod();
        $formData = yii::$app->request->$method();
        
        if(isset($formData['type']) && $formData['type'] == 'ab_test') {
            $verify = $this->verifyAddAbUserGroupSendList($formData);
        } else {
            $verify = $this->verifyAddUserGroupSendList($formData);
        }
        
        if (true !== $verify) {
            $this->sysMsg('警告', "添加分组失败：{$verify}",
                [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
        }
        
        $data = $formData;
        
        $data['boot_time'] = 0;     // 启动时间
        $data['state'] = MailGroup::STATE_STOP;     // 默认状态为停止发送
        $data['send_type'] = 0;
        if (isset($data['send_type_time'])) {
            $data['send_type'] = $data['send_type_time'];
        }
//        if (is_numeric($data['time_zone'])) {      // 如果是定时发送，那么分组状态为启动状态
//            $data['state'] = MailGroup::STATE_START;
//            $data['boot_time'] = time();
//        }

        $data['start_time'] = 0;
        $data['is_fix_time_send'] = 0;
        if (is_numeric($formData['time_zone']) && !empty($formData['time_zone_clock'])) {
            
            $data['state'] = MailGroup::STATE_START;
            $data['boot_time'] = time();
            
            $newSysTime = new \app\components\NewSysTime($formData['time_zone']);
            $data['start_time'] = $newSysTime->strtotime($formData['time_zone_clock']);
            $data['is_fix_time_send'] = 1;
        }
        $data['track_code'] = "utm_source=mail_api&utm_medium=mail&utm_campaign=" . $formData['utm_campaign'];
        
        // 通过template_pk来获取custom_track_code
//        $selectSql = "select custom_track_code from mail_template where id = ".$data['template_pk'];
//        $customTrackCode = Yii::$app->db->createCommand($selectSql)->queryOne();
//        if (!empty($customTrackCode) && !empty($customTrackCode['custom_track_code']))
//        {
//            $data['track_code'] .= '&'.$customTrackCode['custom_track_code'];
//        }
        $data['user_define_group'] = isset($data['user_define_group']) ? $data['user_define_group'] : [];
        $data['sys_group'] = isset($data['sys_group']) ? $data['sys_group'] : [];
        $data['exclude_group'] = isset($data['exclude_group']) ? $data['exclude_group'] : [];
        $data['group_type'] = 2;        // 分群分组
        $data['send_per_minute'] = 1000;        // 每次发送数，默认1000
        if (2 == $data['channel_id']) {     // emarsys通道，每次发送数为20000
            $data['send_per_minute'] = $this->sendPerMinute;
        }
        if (4 == $data['channel_id']) {     // cheet通道，每次发送数为45000
            $data['send_per_minute'] = $this->sendPerMinute;
        }
        
        if (5 == $data['channel_id']) {     // benchmark通道，每次发送数为45000
            // $data['send_per_minute'] = $this->sendPerMinute;
            $data['send_per_minute'] = 1000;
        }
        
         if (9 == $data['channel_id']) { 
            $data['send_per_minute'] = 100;
        }
        $groupModel = new MailGroup();
        $sendListModel = new MailSendlist();
        $statModel = new MailGroupEmailTypeStatistics();
        $userGroupModel = new UserGroup();

        $siteName = Site::getInstance()->getSiteShortNameById($data['site_id']);
        
        $allSelectInfo = [];
        
        if ($data['site_id'] != 31 && ($importType != 'manual')) {
            $allSelectInfo = $userGroupModel->makeMergeTempTable($siteName, $data['user_define_group'], $data['sys_group'], $data['exclude_group']);
        }
        $siteInfo = yii::$app->params['sites']['marketing_email']['web_config'][$siteName]; 
        if (!empty($siteInfo['accessEs'])) {
            $esAllSelectInfo = $userGroupModel->getMergeGroupCountEs($siteName, $data['user_define_group'], $data['sys_group'], $data['exclude_group'],1);
        } else {
            $esAllSelectInfo = "";
        }
      
        $data['select_info'] = $allSelectInfo;
        //对emarsys新旧通道进行上线判定
        
        $isToMax = $this->isToMax($data,2);
        //如果判断结果为true，就给出提示信息
        if($isToMax) {
            $this->sysMsg('警告', "添加分组失败：已超通道限制，请选其他通道！",
                [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
        }
        if ($data['site_id'] == 31 || ($data['site_id'] ==25 && $importType == 'manual')) {
            $data['group_type'] = 3;        // 手动导入
            $detail = [];
            $detailTmp = [];
            
            foreach ($data['user_define_group'] as $dataVal) {
                $detailTmp['type'] = "user_define";
                $detailTmp['form_data'] = "";
                $detailTmp['count'] = "";
                $detailTmp['user_group_id'] = $dataVal;
                $detailTmp['user_group_type'] = 8;
                $detailTmp['user_group_name'] = "";
                $detail[] = $detailTmp;
            }
            
            foreach ($data['exclude_group'] as $dataVal) {
                $detailTmp['type'] = "exclude";
                $detailTmp['form_data'] = "";
                $detailTmp['count'] = "";
                $detailTmp['user_group_id'] = $dataVal;
                $detailTmp['user_group_type'] = 8;
                $detailTmp['user_group_name'] = "";
                $detail[] = $detailTmp;
            }
        } else {
            $detail = $this->getUserGroupCountDetail($data['user_define_group'], $data['sys_group'], $data['exclude_group']); 
        }
        
       
        $data['user_group_detail'] = json_encode($detail);

        // 更新用户分群的使用时间
        $userGroupArr = array_merge($data['user_define_group'], $data['sys_group'], $data['exclude_group']);
        
        $userGroupModel->updateByConditionIn($userGroupArr, ['use_time' => time()]);
      
        // REDIS 发送分组KEY
        //$redisKey='addUserGroupSendList';
        $redisKey = "addUserGroupSendList:{$siteName}";
        
        // 数据库开始事物
        $trans = Yii::$app->db->beginTransaction();
        try {
            // 异步增加用户队列信息
            $redis = new RedisMarketingEmail();
            
            $data['is_build_data'] = 0;
            $this->groupId = $groupId = $groupModel->addGroup($data);
            
            // 增加队列信息
            $redisData = ['site_id'=>$data['site_id'],
                          'group_id'=>$groupId,
                          'channel_id'=>$data['channel_id'],
                          'template_pk'=>$data['template_pk'],
                          'allSelectInfo'=>$allSelectInfo,
                          'esAllSelectInfo'=>$esAllSelectInfo,
                          'is_build_data'=>$data['is_build_data'],
                          'user_count'=>$data['user_count']];
            $redisData=json_encode($redisData);
            $redis->lpush($redisKey, $redisData);
            
            // 增加队列日志
            $groupModel->addGroupQueue($groupId, $redisData, $data['user_count'],$esAllSelectInfo);
            
            // 记录入elog
            Elog::logAdmin($redisData, 'actionAddUserGroupSendList','info');
            
            $trans->commit();
            
            if(isset($data['again-add-send-queue']) && $data['again-add-send-queue'] == 1)
            {
                return $this->redirect(['/marketing/user-group/index?site=marketing_email']);
            }
            else
            {
                return $this->redirect(['/marketing/mail-group/send-group-list?site=marketing_email']);
            }
            //echo "添加分组成功, 分组id[{$groupId}].跳转到发送分组页面....";
        } catch (\Exception $e) {
            var_dump($e->getMessage(),$e->getTraceAsString());
            
            if(!empty($this->groupId)) { 
                // 创建分组失败,REDIS执行回滚
                $redis->lpop($redisKey);
            }
            
            $trans->rollBack();
            exit("添加分组失败：系统繁忙，请稍后重试");
        }
    }
    
    /*
     * 判断指定站点是否存在相同的测试分组名称
     */
    public function actionGetSiteTestGroupName()
    {
        $method = yii::$app->request->getMethod();
        $formData = yii::$app->request->$method();
        $siteId = $formData['site_id'] ? intval($formData['site_id']) : 0;
        $testGroupName = $formData['test_group_name'] ? trim($formData['test_group_name']) : '';
        if(!$siteId || !$testGroupName) {
            $this->returnJson(0, "参数有误！");
        }
        $groupModel = new MailGroup();
        $whereArr = [
            'group_name' => $testGroupName,
            'site_id' => $siteId,
            'is_ab_test' => 1,
            'ab_test_parent_id' => 0
        ];
        if($groupModel->getGroupByCondition($whereArr)) {
            $this->returnJson(0, "该名称已被使用，请重新输入！");
        } else {
            $this->returnJson(1, "");
        }
    }
    
     /**
     * 添加分群的发送队列
     */
    public function actionAddTestUserGroupSendList()
    {
        ini_set('memory_limit', '1024M');
        
        $method = yii::$app->request->getMethod();
        $formData = yii::$app->request->$method();
        
        $verify = $this->verifyAddAbUserGroupSendList($formData);
        
        
        if (true !== $verify) {
            $this->sysMsg('警告', "添加分组失败：{$verify}",
                [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
        }
        
        $data = $formData;
        
        $data['boot_time'] = 0;     // 启动时间
        $data['state'] = MailGroup::STATE_STOP;     // 默认状态为停止发送
        $data['send_type'] = 0;
        $data['send_mode'] = 2;
        if (isset($data['send_type_time'])) {
            $data['send_type'] = $data['send_type_time'];
        }
//        if (is_numeric($data['time_zone'])) {      // 如果是定时发送，那么分组状态为启动状态
//            $data['state'] = MailGroup::STATE_START;
//            $data['boot_time'] = time();
//        }

        $data['start_time'] = 0;
        $data['is_fix_time_send'] = 0;
        if (is_numeric($formData['time_zone']) && !empty($formData['time_zone_clock'])) {
            
            $data['state'] = MailGroup::STATE_START;
            $data['boot_time'] = time();
            
            $newSysTime = new \app\components\NewSysTime($formData['time_zone']);
            $data['start_time'] = $newSysTime->strtotime($formData['time_zone_clock']);
            $data['is_fix_time_send'] = 1;
        }
        
        $groupModel = new MailGroup();
        $sendListModel = new MailSendlist();
        $statModel = new MailGroupEmailTypeStatistics();
        $userGroupModel = new UserGroup();
        $redis = new RedisMarketingEmail();
        
        if(is_numeric($formData['ab_test_mail_group_id'])) {
            $abTestGroup = $groupModel->getAbTestMailGroup($formData['ab_test_mail_group_id']);
            $abTestChildGroups = $groupModel->getAbTestChildMailGroup($formData['ab_test_mail_group_id']);
            if(count($abTestChildGroups) < 2) {
                $this->sysMsg('警告', "当前A/B测试所设置的分组数量不足2个，请设置至数量要求方范围内。",
                [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
            }
            
            $templateId = 0;
            foreach($abTestChildGroups as $abTestChildGroup) {
                if(isset($abTestChildGroup['template_id']) && $abTestChildGroup['template_id'] > 0) {
                    $templateId = $abTestChildGroup['template_id'];
                    break;
                }
                
            }
            if(isset($abTestGroup)) {
                $data['group_name'] = $data['ab_test_user_group_name'];
                $data['template_id'] = $templateId;
                $data['template_pk'] = $templateId;
                $data['track_code'] = '';
                $data['is_ab_test'] = 1;
                $data['user_define_group'] = isset($data['user_define_group']) ? $data['user_define_group'] : [];
                $data['sys_group'] = isset($data['sys_group']) ? $data['sys_group'] : [];
                $data['exclude_group'] = isset($data['exclude_group']) ? $data['exclude_group'] : [];
                $data['group_type'] = 2;        // 分群分组
                $data['send_per_minute'] = 1000;        // 每次发送数，默认1000
                if (2 == $data['channel_id']) {     // emarsys通道，每次发送数为20000
                    $data['send_per_minute'] = $this->sendPerMinute;
                }
                if (4 == $data['channel_id']) {     // cheet通道，每次发送数为45000
                    $data['send_per_minute'] = $this->sendPerMinute;
                }
                if (5 == $data['channel_id']) {     // benchmark通道，每次发送数为45000
                    // $data['send_per_minute'] = $this->sendPerMinute;
                    $data['send_per_minute'] = 1000;
                }
                if (9 == $data['channel_id']) { 
                    $data['send_per_minute'] = 100;
                }
                $siteName = Site::getInstance()->getSiteShortNameById($data['site_id']);

                $allSelectInfo = [];
                if ($data['site_id'] != 31) {
                    $allSelectInfo = $userGroupModel->makeMergeTempTable($siteName, $data['user_define_group'], $data['sys_group'], $data['exclude_group']);
                }


                $data['select_info'] = $allSelectInfo;
                //对emarsys新旧通道进行上线判定

                $isToMax = $this->isToMax($data,2);
                //如果判断结果为true，就给出提示信息
                if($isToMax) {
                    $this->sysMsg('警告', "添加分组失败：已超通道限制，请选其他通道！",
                        [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
                }
                if ($data['site_id'] == 31) {
                    $detail = [];
                    $detailTmp = [];

                    foreach ($data['user_define_group'] as $dataVal) {
                        $detailTmp['type'] = "user_define";
                        $detailTmp['form_data'] = "";
                        $detailTmp['count'] = "";
                        $detailTmp['user_group_id'] = $dataVal;
                        $detailTmp['user_group_type'] = 8;
                        $detailTmp['user_group_name'] = "";
                        $detail[] = $detailTmp;
                    }

                    foreach ($data['exclude_group'] as $dataVal) {
                        $detailTmp['type'] = "exclude";
                        $detailTmp['form_data'] = "";
                        $detailTmp['count'] = "";
                        $detailTmp['user_group_id'] = $dataVal;
                        $detailTmp['user_group_type'] = 8;
                        $detailTmp['user_group_name'] = "";
                        $detail[] = $detailTmp;
                    }
                } else {
                    $detail = $this->getUserGroupCountDetail($data['user_define_group'], $data['sys_group'], $data['exclude_group']); 
                }

                
                $data['user_group_detail'] = json_encode($detail);

                // 更新用户分群的使用时间
                $userGroupArr = array_merge($data['user_define_group'], $data['sys_group'], $data['exclude_group']);
                $userGroupModel->updateByConditionIn($userGroupArr, ['use_time' => time()]);
      
                // REDIS 发送分组KEY
                $redisKey='addUserGroupSendList:'.$siteName;

                // 数据库开始事物
                $trans = Yii::$app->db->beginTransaction();
                try {
                    // 异步增加用户队列信息

                    $data['is_build_data'] = 0;
                    $this->groupId = $groupId = $groupModel->addGroup($data);

                    // 增加队列信息
                    $redisData = ['site_id'=>$data['site_id'],
                                  'group_id'=>$groupId,
                                  'channel_id'=>$data['channel_id'],
                                  'template_pk'=>$data['template_pk'],
                                  'allSelectInfo'=>$allSelectInfo,
                                  'is_build_data'=>$data['is_build_data'],
                                  'user_count'=>$data['user_count'],
                                  'is_ab_test' => 1,
                                  'ab_test_parent_id' => 0
                                ];
                    $redisData=json_encode($redisData);
                    $redis->lpush($redisKey, $redisData);

                    // 增加队列日志
                    $groupModel->addGroupQueue($groupId, $redisData, $data['user_count']);

                    // 记录入elog
                    Elog::logAdmin($redisData, 'actionAddUserGroupSendList','info');

                    $trans->commit();

                    
                //echo "添加分组成功, 分组id[{$groupId}].跳转到发送分组页面....";
                } catch (\Exception $e) {
                    var_dump($e->getMessage(),$e->getTraceAsString());

                    if(!empty($this->groupId)) { 
                        // 创建分组失败,REDIS执行回滚
                        $redis->lpop($redisKey);
                    }

                    $trans->rollBack();
                    exit("添加分组失败：系统繁忙，请稍后重试");
                }
            }
            $templateModel = new MailTemplate();
            // 添加测试子分组数据到分组表
            if(isset($abTestChildGroups)) {
                // 数据库开始事物
                $trans = Yii::$app->db->beginTransaction();
                try {
                    
                    foreach($abTestChildGroups as $abTestChildGroup) {
                        
                        
                        $template = $templateModel->getAbTestTemplateDetailById($data['site_id'], $abTestChildGroup['template_id']);
                        $template = array_shift($template);
                        
                        $curBjTime = \yii::$app->bjTime->time();
                        $curBjDate = \yii::$app->bjTime->date('ymd',$curBjTime);
            
                        $template['track_code'] = str_replace("{sendTime}", $curBjTime, $template['track_code']);
                        $template['track_code'] = str_replace("{sendDate}", $curBjDate, $template['track_code']);
                        
                        $data['track_code'] = "utm_source=mail_api&utm_medium=mail&utm_campaign=" . $template['track_code'];
                        $data['group_name'] = $template['track_code'];
                        $data['template_id'] = $template['id'];
                        $data['template_pk'] = $template['id'];
                        $data['is_ab_test'] = 1;
                       
                        $data['ab_test_parent_id'] = $groupId;
                        $data['ab_test_real_id'] = $abTestChildGroup['id'];
                        
                        $data['user_group_detail'] = '';
                        $data['user_define_group'] = []; 
                        $data['sys_group'] = []; 
                        $data['exclude_group'] = [];
                       

                        $data['group_type'] = 2;        // 分群分组
                        $data['send_per_minute'] = 1000;        // 每次发送数，默认1000
                        if (2 == $data['channel_id']) {     // emarsys通道，每次发送数为20000
                            $data['send_per_minute'] = $this->sendPerMinute;
                        }
                        if (4 == $data['channel_id']) {     // cheet通道，每次发送数为45000
                            $data['send_per_minute'] = $this->sendPerMinute;
                        }
                        if (5 == $data['channel_id']) {     // benchmark通道，每次发送数为45000
                            // $data['send_per_minute'] = $this->sendPerMinute;
                            $data['send_per_minute'] = 1000;
                        }
                        
                        if (9 == $data['channel_id']) { 
                            $data['send_per_minute'] = 100;
                        }
                        $siteName = Site::getInstance()->getSiteShortNameById($data['site_id']);


                        // REDIS 发送分组KEY
                        $redisKey='addUserGroupSendList:'.$siteName;

                        

                            // 异步增加用户队列信息


                        $data['is_build_data'] = 0;
                        $childGroupId = $groupModel->addGroup($data);
                        
                        // 增加队列信息
                        $redisData = ['site_id'=>$data['site_id'],
                                      'group_id'=>$childGroupId,
                                      'channel_id'=>$data['channel_id'],
                                      'template_pk'=>$data['template_pk'],
                                      'is_build_data'=>$data['is_build_data'],
                                      'is_ab_test' => 1,
                                      'ab_test_parent_id' => $groupId
                                    ];
                        $redisData=json_encode($redisData);
                        $redis->lpush($redisKey, $redisData);

                        // 增加队列日志
                        $groupModel->addGroupQueue($childGroupId, $redisData, 0);
                        
                    }
                    $trans->commit();
                 //echo "添加分组成功, 分组id[{$groupId}].跳转到发送分组页面....";
                } catch (\Exception $e) {
                    var_dump($e->getMessage(),$e->getTraceAsString());

                    $trans->rollBack();
                    exit("添加分组失败：系统繁忙，请稍后重试");
                }
            }
            if(isset($data['again-add-send-queue']) && $data['again-add-send-queue'] == 1)
            {
                return $this->redirect(['/marketing/user-group/index?site=marketing_email&type=ab_test']);
            }
            else
            {
                return $this->redirect(['/marketing/mail-group/send-group-list?site=marketing_email']);
            }
        }
        
        
        
    }

    /**
     * 获取用户分群数详情
     * @param $userDefineGroup
     * @param $sysGroup
     * @param $excludeGroup
     * @return array
     */
    public function getUserGroupCountDetail($userDefineGroup, $sysGroup, $excludeGroup)
    {
        $userGroupModel = new UserGroup();
        $detail = [];
        foreach ($userDefineGroup as $value) {
            $groupArr = $userGroupModel->getByCondition(["user_group_id" => $value]);
            if (empty($groupArr)) {
                continue;
            }
            $group = $groupArr[0];
            $siteName = Site::getInstance()->getSiteShortNameById($group['site_id']);
            $regCon = json_decode($group['reg_con'], true);
            $loginCon = json_decode($group['login_con'], true);
            $orderCon = json_decode($group['order_con'], true);
            $mailCon = json_decode($group['mail_con'], true);
            $cateCon = json_decode($group['cate_con'], true);
            $userBehaviorCateCon = json_decode($group['user_behavior_cate_con'],true);
            $userLabelCon = json_decode($group['user_label_con'],true);
            $count = $userGroupModel->getCount($siteName, $group['user_group_id'], $regCon, $loginCon, $orderCon, $mailCon,$cateCon,$userBehaviorCateCon,$userLabelCon);
            $detail[] = ['type' => 'user_define','form_data' => $group['form_data'], 'count' => $count, 'user_group_id' => $value,
                'user_group_type' => $group['user_group_type'], 'user_group_name' => $group['user_group_name']];
        }

        foreach ($sysGroup as $value) {
            $groupArr = $userGroupModel->getByCondition(["user_group_id" => $value]);
            if (empty($groupArr)) {
                continue;
            }
            $group = $groupArr[0];
            $detail[] = ['type' => 'sys', 'form_data' => $group['form_data'], 'count' => '', 'user_group_id' => $value,
                'user_group_type' => $group['user_group_type'], 'user_group_name' => $group['user_group_name']];
        }

        foreach ($excludeGroup as $value) {
            $groupArr = $userGroupModel->getByCondition(["user_group_id" => $value]);
            if (empty($groupArr)) {
                continue;
            }
            $group = $groupArr[0];
            if (1 == $group['user_group_type']) {
                $siteName = Site::getInstance()->getSiteShortNameById($group['site_id']);
                $regCon = json_decode($group['reg_con'], true);
                $loginCon = json_decode($group['login_con'], true);
                $orderCon = json_decode($group['order_con'], true);
                $mailCon = json_decode($group['mail_con'], true);
                $cateCon = json_decode($group['cate_con'],true);
                $userBehaviorCateCon = json_decode($group['user_behavior_cate_con'],true);
                $count = $userGroupModel->getCount($siteName, $group['user_group_id'], $regCon, $loginCon, $orderCon, $mailCon, $cateCon,$userBehaviorCateCon);
            } else {
                $count = '';    // 系统分组不用计算数量
            }
            $detail[] = ['type' => 'exclude', 'form_data' => $group['form_data'], 'count' => $count, 'user_group_id' => $value,
                'user_group_type' => $group['user_group_type'], 'user_group_name' => $group['user_group_name']];
        }
        return $detail;
    }

    /**
     * 校验发送队列提交的参数
     * @param $formData
     * @return bool|string
     */
    private function verifyAddUserGroupSendList($formData)
    {
        if (!isset($formData['group_name'])) {
            return "没有分组名称";
        }
        if (!isset($formData['utm_campaign'])) {
            return "没有utm_campaign";
        }
        if (!isset($formData['site_id'])) {
            return "没有网站ID";
        }
        if (!isset($formData['template_id']) || !is_numeric($formData['template_pk'])) {
            return "请选择模板";
        }
        if (!isset($formData['send_mode'])) {
            return "请选择发送方式";
        }
        if (1 == $formData['send_mode'] && !isset($formData['send_type_time'])) {
            return "请选择邮件发送的天数";
        }
        if (isset($formData['time_zone'])) {
            if (!isset($formData['time_zone_clock'])) {
                return "请填写所选时区的时间";
            }
        }
        if (!isset($formData['user_define_group']) && !isset($formData['sys_group']))
        {
            return "自定义分群，系统分群至少选择一个";
        }

        if (empty($formData['channel_id'])) {
            return "请选择通道";
        }
        if (empty($formData['sender'])) {
            return "请提交发送邮箱";
        }
        if (empty($formData['user_count'])) {
            return "用户数为0，不支持添加分组";
        }
        return true;
    }
    
    
    /**
     * 校验ab测试发送队列提交的参数
     * @param $formData
     * @return bool|string
     */
    private function verifyAddAbUserGroupSendList($formData)
    {
        
        if (!isset($formData['site_id'])) {
            return "没有网站ID";
        }
        if (!isset($formData['ab_test_user_group_name'])) {
            return "请输入A/B测试名称";
        }
        if (!isset($formData['contrastive-term']) || !is_numeric($formData['contrastive-term'])) {
            return "请选择对比项";
        }
        if (isset($formData['time_zone'])) {
            if (!isset($formData['time_zone_clock'])) {
                return "请填写所选时区的时间";
            }
        }
        if (!isset($formData['user_define_group']) && !isset($formData['sys_group']))
        {
            return "自定义分群，系统分群至少选择一个";
        }

        if (empty($formData['channel_id'])) {
            return "请选择通道";
        }
        if (empty($formData['sender'])) {
            return "请提交发送邮箱";
        }
        if (empty($formData['user_count'])) {
            return "用户数为0，不支持添加分组";
        }
        return true;
    }
    /**
     * 已经发完的分组发送用户明细
     */
   
    public function actionSendUserHistoryList()
    {
        
        Yii::$app->params['now_addr'] = "发送记录";
        $mothod = strtolower(Yii::$app->request->getMethod());
        $data = [];
        $defaultPageSize = 20;
        $site = Yii::$app->request->$mothod('site');
        $formData = Yii::$app->request->$mothod();
        if (empty($formData['group_id'])) {
           exit('传递数据有误');  
        } else {
            // 分页参数相关
            $page = Yii::$app->request->$mothod('page') ? Yii::$app->request->$mothod('page') : 1;
            $pageSize = Yii::$app->request->$mothod('pagesize') ? Yii::$app->request->$mothod('pagesize') : $defaultPageSize;
            $formData['page'] = $page;
            $formData['pageSize'] = $pageSize;
            // 先获取分组的相关信息
            $groupModel = new \app\models\marketing\MailGroup();
            $groupInfo = $groupModel->getGroupAndTemp($formData['group_id']);
            
           
            // 相关的模版信息
            $groupInfo['add_date'] = \yii::$app->bjTime->date("Y-m-d H:i",$groupInfo['add_date']);
            $groupInfo['template_subject_brief'] = substr($groupInfo['template_subject'],0,45);
            if (empty($groupInfo)) {
                exit('分组信息不存在');
            }
            if (!isset($formData['state'])) {
                $formData['state'] = -1;
            }
            
            if(!isset($formData['send_status'])) {
                $formData['send_status'] = -1;
            }
            // 获取当前发送列表的相关信息
            $sendListModel = new \app\models\marketing\MailSendlist();
            $sendListInfo = $sendListModel->sendList($groupInfo['site_id'],$formData['group_id'],$formData);
            
            
            // 数据处理相关
           
            foreach ($sendListInfo['sendList'] as $sendListK => $sendListV) {
                
                // 邮箱处理
                $sendListInfo['sendList'][$sendListK]['email'] = Yii::$app->email->emailDispProcess(Yii::$app->emailmarket->decryption($sendListV['email']));
                
                // 发送时间处理
                $sendListInfo['sendList'][$sendListK]['last_send'] = $sendListV['last_send'] ? \yii::$app->bjTime->date('Y-m-d H:i',$sendListV['last_send']) : "--";
                
                // 发送状态处理
                if ($sendListV['send_status'] == 0) {
                    $sendListInfo['sendList'][$sendListK]['send_status'] = "--";
                } elseif ($sendListV['send_status'] == 1) {
                     $sendListInfo['sendList'][$sendListK]['send_status'] = "发送成功";
                } elseif ($sendListV['send_status'] == 2) {
                    $sendListInfo['sendList'][$sendListK]['send_status'] = "发送失败";
                } elseif($sendListV['state'] == 3) { // edm端发送失败
                   $sendListInfo['sendList'][$sendListK]['send_status'] = "发送失败"; 
                } else {
                    $sendListInfo['sendList'][$sendListK]['send_status'] = "--"; 
                } 
            }
            
            $totalCount = $sendListInfo['totalCount'];
            // 分页相关
            $pages = new Pagination(['totalCount' =>$totalCount, 'pageSize' => $pageSize, 'defaultPageSize' => $pageSize]);
           
            
            
        }
       
       
        return $this->render("//marketing/mail-group/send-user-history-list", [
            'data' => $sendListInfo['sendList'],
            'formData' => $formData,
            'site' => $site,
            'groupInfo' => $groupInfo,
            'pages' => $pages,
        ]);
    }
    /**
     * 发送用户明细
     */
    public function actionSendUserList()
    {        
        Yii::$app->params['now_addr'] = "发送管理";
        $mothod = strtolower(Yii::$app->request->getMethod());
        $data = [];
        $defaultPageSize = 20;
        $site = Yii::$app->request->$mothod('site');
        $formData = Yii::$app->request->$mothod();
        if (empty($formData['group_id'])) {
           exit('传递数据有误');  
        } else {
            // 分页参数相关
            $page = Yii::$app->request->$mothod('page') ? Yii::$app->request->$mothod('page') : 1;
            $pageSize = Yii::$app->request->$mothod('pagesize') ? Yii::$app->request->$mothod('pagesize') : $defaultPageSize;
            $formData['page'] = $page;
            $formData['pageSize'] = $pageSize;
            // 先获取分组的相关信息
            $groupModel = new \app\models\marketing\MailGroup();
            $groupInfo = $groupModel->getGroupAndTemp($formData['group_id']);
            $channelArr = [2 => 'emarsys', 4 => 'cheet', 6 => 'emarsys_new', 5 => 'benchmark', 9 => 'webpower'];
           
            $groupInfo['channel_name'] = $channelArr[$groupInfo['channel_id']];
            // 相关的模版信息
            $groupInfo['add_date'] = \yii::$app->bjTime->date("Y-m-d H:i",$groupInfo['add_date']);
            $groupInfo['template_subject_brief'] = substr($groupInfo['template_subject'],0,45);
            if (empty($groupInfo)) {
                exit('分组信息不存在');
            }
            
            if(!isset($formData['state'])) { // 全部
                $formData['state'] = -1; 
            }
            
            // 根据邮箱来搜索
            if (isset($formData['email']) && trim($formData['email'])) {
                $formData['email'] = trim($formData['email']);
                $formData['state'] = -1;
            }
            
            if(!isset($formData['send_status'])) {
                $formData['send_status'] = -1;
            }
            // 获取当前发送列表的相关信息
            $sendListModel = new \app\models\marketing\MailSendlist();
            $sendListInfo = $sendListModel->sendList($groupInfo['site_id'],$formData['group_id'],$formData);
            $splitSendlist = new SplitSendlist();
            $splitFlag = $splitSendlist->judgeSplitStatisticsData($formData['group_id']); // 统计数据从sendlist表中拆分出来
            if ($splitFlag) { // 统计数据从sendlist表中拆分出来
                foreach ($sendListInfo['sendList'] as $sendListK => $sendListV) {
                    // 邮箱处理
                    $sendListInfo['sendList'][$sendListK]['email'] = Yii::$app->email->emailDispProcess(Yii::$app->emailmarket->decryption($sendListV['email']));
                    // 发送时间处理
                    $sendListInfo['sendList'][$sendListK]['last_send'] = $sendListV['last_send'] ? \yii::$app->bjTime->date('Y-m-d H:i',$sendListV['last_send']) : "--";
                    
                    // 发送状态处理
                    if (isset($sendListV['send_status_split']) && $sendListV['send_status_split'] === 0) {
                        $sendListInfo['sendList'][$sendListK]['state'] = "发送失败";
                    } elseif(!isset($sendListV['state']) || $sendListV['state'] === null) {
                        $sendListInfo['sendList'][$sendListK]['state'] = "未发送";
                    } elseif($sendListV['state'] === 0) {
                        $sendListInfo['sendList'][$sendListK]['state'] = "停止发送";
                    } elseif($sendListV['state'] == 6) { 
                        $sendListInfo['sendList'][$sendListK]['state'] = "切割中";
                    } elseif ($sendListV['state'] == 1) {
                        $sendListInfo['sendList'][$sendListK]['state'] = "加入队列中";
                    } elseif ($sendListV['state'] == 2) {
                        $sendListInfo['sendList'][$sendListK]['state'] = "已推送"; 
                    } elseif ($sendListV['state'] == 3) {
                        $sendListInfo['sendList'][$sendListK]['state'] = "系统推送失败";
                    } elseif ($sendListV['state'] == 4) {
                        $sendListInfo['sendList'][$sendListK]['state'] = "重发中";
                    } elseif ($sendListV['state'] == 5) {
                        $sendListInfo['sendList'][$sendListK]['state'] = "停止重发";
                    } else {
                        $sendListInfo['sendList'][$sendListK]['state'] = "未知";
                    }
                }
            } else {
                // 数据处理相关
                foreach ($sendListInfo['sendList'] as $sendListK => $sendListV) {

                    // 邮箱处理
                    $sendListInfo['sendList'][$sendListK]['email'] = Yii::$app->email->emailDispProcess(Yii::$app->emailmarket->decryption($sendListV['email']));

                    // 发送时间处理
                    $sendListInfo['sendList'][$sendListK]['last_send'] = $sendListV['last_send'] ? \yii::$app->bjTime->date('Y-m-d H:i',$sendListV['last_send']) : "--";

                    // 发送状态处理
                    if ($sendListV['state'] == 0) {
                        $sendListInfo['sendList'][$sendListK]['state'] = "未发送";
                    } elseif($sendListV['state'] == 6) { 
                        $sendListInfo['sendList'][$sendListK]['state'] = "切割中";
                    } elseif ($sendListV['state'] == 1) {
                        $sendListInfo['sendList'][$sendListK]['state'] = "加入队列中";
                    } elseif ($sendListV['state'] == 2) {

                        if ($sendListV['send_status'] == 0) {
                            $sendListInfo['sendList'][$sendListK]['state'] = "已推送";
                        } elseif ($sendListV['send_status'] == 1) {
                             $sendListInfo['sendList'][$sendListK]['state'] = "发送成功";
                        } elseif ($sendListV['send_status'] == 2) {
                            $sendListInfo['sendList'][$sendListK]['state'] = "发送失败";
                        } else {
                            $sendListInfo['sendList'][$sendListK]['state'] = "已推送"; 
                        } 

                    } elseif ($sendListV['state'] == 3) {
                        $sendListInfo['sendList'][$sendListK]['state'] = "系统推送失败";
                    }

                }
            }
            
            
            $totalCount = $sendListInfo['totalCount'];
            // 分页相关
            $pages = new Pagination(['totalCount' =>$totalCount, 'pageSize' => $pageSize, 'defaultPageSize' => $pageSize]);
           
            
            
        }
       
       
        return $this->render("//marketing/mail-group/send-user-list", [
            'data' => $sendListInfo['sendList'],
            'formData' => $formData,
            'site' => $site,
            'groupInfo' => $groupInfo,
            'pages' => $pages,
        ]);
    }


    /**
     * 显示用户分群
     * @return string
     */
    public function actionShowUserGroup()
    {
        yii::$app->params['now_addr'] = "发送管理";
        $method = yii::$app->request->getMethod();
        $mailGroupId = yii::$app->request->$method("group_id");
        if (empty($mailGroupId)) {
            $this->sysMsg('警告', '数据不完整，缺少分组id!',
                [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
        }
        $groupModel = new MailGroup();
        $group = $groupModel->getGroupById($mailGroupId);
        
       
        $data = $group;
        $detail = json_decode($group['user_group_detail'], true);
        $preview = ["user_define" => [], "sys" => [], "exclude" => []];
       
        foreach ($detail as $key => $value) {
            $formData = json_decode($value['form_data'], true);
            $item = $this->getPreviewItem($formData);
            
            $detail[$key]['item'] = $item;
            $preview[$value['type']][] = $detail[$key];
        }
        $data['preview'] = $preview;
        if ($data['site_id'] == 31 || ($data['site_id']==25 && $data['group_type']==3) ) {
            $userGroupIdArr = [];
            if ($data['preview']['user_define']) {
                foreach ($data['preview']['user_define'] as $userDefineOne) {
                    $userGroupIdArr[] = $userDefineOne['user_group_id'];
                }
            } 
            if ($data['preview']['exclude']) {
                foreach ($data['preview']['exclude'] as $excludeOne) {
                    $userGroupIdArr[] = $excludeOne['user_group_id'];
                }
            }
            
            // 根据user_group_id
            $userGroup= new UserGroup();
            $userGroupInfoArr = $userGroup->getUserGroupByIdArr($userGroupIdArr);
            $userGroupInfoArrDeal = [];
            foreach ($userGroupInfoArr as $userGroupInfoArrVal) {
                $userGroupInfoArrDeal[$userGroupInfoArrVal['user_group_id']] = $userGroupInfoArrVal;
            }
            if ($data['preview']['user_define']) {
                foreach ($data['preview']['user_define'] as $key => $userDefineOne) {
                    if (!empty($userGroupInfoArrDeal[$userDefineOne['user_group_id']])) {
                        $data['preview']['user_define'][$key]['item'][0]['name'] = $data['preview']['user_define'][$key]['user_group_name'] = $userGroupInfoArrDeal[$userDefineOne['user_group_id']]['user_group_name'];
                        $data['preview']['user_define'][$key]['item'][0]['count'] = $data['preview']['user_define'][$key]['count'] = $userGroupInfoArrDeal[$userDefineOne['user_group_id']]['user_count'];
                    } else {
                        $data['preview']['user_define'][$key]['item'][0]['name'] = $data['preview']['user_define'][$key]['user_group_name'] = "";
                        $data['preview']['user_define'][$key]['item'][0]['count'] = $data['preview']['user_define'][$key]['count'] = 0;
                    }
                    
                }
            } 
            if ($data['preview']['exclude']) {
                foreach ($data['preview']['exclude'] as $key => $excludeOne) {
                    if (!empty($userGroupInfoArrDeal[$excludeOne['user_group_id']])) {
                        $data['preview']['exclude'][$key]['item'][0]['name'] = $data['preview']['exclude'][$key]['user_group_name'] = $userGroupInfoArrDeal[$excludeOne['user_group_id']]['user_group_name'];
                        $data['preview']['exclude'][$key]['item'][0]['count'] = $data['preview']['exclude'][$key]['count'] = $userGroupInfoArrDeal[$excludeOne['user_group_id']]['user_count'];
                    } else {
                        $data['preview']['exclude'][$key]['item'][0]['name'] = $data['preview']['exclude'][$key]['user_group_name'] = "";
                        $data['preview']['exclude'][$key]['item'][0]['count'] = $data['preview']['exclude'][$key]['count'] = 0;
                    }
                }
            }
            return $this->render("//marketing/mail-group/show-ebay-group", ["data" => $data]);
        } else {
            return $this->render("//marketing/mail-group/show-user-group", ["data" => $data]);
        }
        
    }

    /**
     * 显示用户分群
     * @return string
     */
    public function actionShowAbTestUserGroup()
    {
        yii::$app->params['now_addr'] = "发送管理";
        $method = yii::$app->request->getMethod();
        $mailGroupId = yii::$app->request->$method("group_id");
        if (empty($mailGroupId)) {
            $this->sysMsg('警告', '数据不完整，缺少分组id!',
                [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
        }
        $groupModel = new MailGroup();
        $sendListModel = new MailSendlist();
        $group = $groupModel->getGroupById($mailGroupId);
        
        // 获取ab测试分组发送量
        $testGroups = $groupModel->getTestChildsSendNumsByGroupId($mailGroupId);
        // TODO 这里是不是有问题？
        $noSendNums = $sendListModel->getSendCountByGroupId($group['site_id'], $mailGroupId);
        $testGroupData = ['total_count' => 0, 'total_users_percent' => 0, 'noSendNums' => $noSendNums['nums']];
        foreach($testGroups as $testGroup) {
            $testGroupData['total_count'] += $testGroup['total_count'];
            $testGroupData['total_users_percent'] += $testGroup['send_users_percent'];
        }
        
       
        $data = $group;
        $detail = json_decode($group['user_group_detail'], true);
        $preview = ["user_define" => [], "sys" => [], "exclude" => []];
       
        foreach ($detail as $key => $value) {
            $formData = json_decode($value['form_data'], true);
            $item = $this->getPreviewItem($formData);
            
            $detail[$key]['item'] = $item;
            $preview[$value['type']][] = $detail[$key];
        }
        $data['preview'] = $preview;
        if ($data['site_id'] == 31 ) {
            $userGroupIdArr = [];
            if ($data['preview']['user_define']) {
                foreach ($data['preview']['user_define'] as $userDefineOne) {
                    $userGroupIdArr[] = $userDefineOne['user_group_id'];
                }
            } 
            if ($data['preview']['exclude']) {
                foreach ($data['preview']['exclude'] as $excludeOne) {
                    $userGroupIdArr[] = $excludeOne['user_group_id'];
                }
            }
            
            // 根据user_group_id
            $userGroup= new UserGroup();
            $userGroupInfoArr = $userGroup->getUserGroupByIdArr($userGroupIdArr);
            $userGroupInfoArrDeal = [];
            foreach ($userGroupInfoArr as $userGroupInfoArrVal) {
                $userGroupInfoArrDeal[$userGroupInfoArrVal['user_group_id']] = $userGroupInfoArrVal;
            }
            if ($data['preview']['user_define']) {
                foreach ($data['preview']['user_define'] as $key => $userDefineOne) {
                    if (!empty($userGroupInfoArrDeal[$userDefineOne['user_group_id']])) {
                        $data['preview']['user_define'][$key]['item'][0]['name'] = $data['preview']['user_define'][$key]['user_group_name'] = $userGroupInfoArrDeal[$userDefineOne['user_group_id']]['user_group_name'];
                        $data['preview']['user_define'][$key]['item'][0]['count'] = $data['preview']['user_define'][$key]['count'] = $userGroupInfoArrDeal[$userDefineOne['user_group_id']]['user_count'];
                    } else {
                        $data['preview']['user_define'][$key]['item'][0]['name'] = $data['preview']['user_define'][$key]['user_group_name'] = "";
                        $data['preview']['user_define'][$key]['item'][0]['count'] = $data['preview']['user_define'][$key]['count'] = 0;
                    }
                    
                }
            } 
            if ($data['preview']['exclude']) {
                foreach ($data['preview']['exclude'] as $key => $excludeOne) {
                    if (!empty($userGroupInfoArrDeal[$excludeOne['user_group_id']])) {
                        $data['preview']['exclude'][$key]['item'][0]['name'] = $data['preview']['exclude'][$key]['user_group_name'] = $userGroupInfoArrDeal[$excludeOne['user_group_id']]['user_group_name'];
                        $data['preview']['exclude'][$key]['item'][0]['count'] = $data['preview']['exclude'][$key]['count'] = $userGroupInfoArrDeal[$excludeOne['user_group_id']]['user_count'];
                    } else {
                        $data['preview']['exclude'][$key]['item'][0]['name'] = $data['preview']['exclude'][$key]['user_group_name'] = "";
                        $data['preview']['exclude'][$key]['item'][0]['count'] = $data['preview']['exclude'][$key]['count'] = 0;
                    }
                }
            }
            return $this->render("//marketing/mail-group/show-ab-test-ebay-group", ["data" => $data, 'testGroup'=> $testGroupData]);
        } else {
            return $this->render("//marketing/mail-group/show-ab-test-user-group", ["data" => $data, 'testGroup'=> $testGroupData]);
        }
        
    }
    /**
     * 获取预览中的选项
     * @param $formData
     * @return array
     */
    public function getPreviewItem($formData)
    {
        $item = [];

        $freqNameArr = [
            "1" => "1次",
            "2" => "2~4次",
            "3" => "5~7次",
            "4" => "8~9次",
            "5" => "10次以上"
        ];
        $orderMoneyArr = [
            "1" => "0$~50$",
            "2" => "50$~100$",
            "3" => "100$~200$",
            "4" => "200$~300$",
            "5" => "300$~500$",
            "6" => '500$以上'
        ];
        // 注册
        if (0 != $formData['register_state']) {
            $regName = "";
            if (1 == $formData['register_time_type']) {        // 指定近几天
                if (!empty(is_numeric($formData['register_near_days']))) {
                    $regName .= "近{$formData['register_near_days']}天 ";
                }
            } else {
                if (!empty($formData['register_start_time'])) {
                    $regName .= "{$formData['register_start_time']}";
                }
                if (!empty($formData['register_end_time'])) {
                    $regName .= "~{$formData['register_end_time']} ";
                }
            }
            if (1 == $formData['register_state']) {
                $regName .= "未注册";
            } else {
                $regName .= "注册";
            }
            //$regCount = $userGroupModel->getCount($siteName, 0, $data['reg_con'], [], [], []);
            $item[] = ["name" => $regName, "count" => ""];
        }

        // 登录
        if (0 != $formData['login_state']) {
            $name = "";
            if (1 == $formData['login_time_type']) {        // 指定近几天
                if (!empty(is_numeric($formData['login_near_days']))) {
                    $name .= "近{$formData['login_near_days']}天 ";
                }
            } else {
                if (!empty($formData['login_start_time'])) {
                    $name .= "{$formData['login_start_time']}";
                }
                if (!empty($formData['login_end_time'])) {
                    $name .= "~{$formData['login_end_time']} ";
                }
            }
            if (1 == $formData['login_state']) {
                $name .= "从未登录";
            } else {
                $name .= "登录";
            }
            if (!empty($formData['login_frequency']) && key_exists($formData['login_frequency'], $freqNameArr)) {
                $name .= " {$freqNameArr[$formData['login_frequency']]} ";
            }
            //$loginCount = $userGroupModel->getCount($siteName, 0, [], $data['login_con'], [], []);
            $item[] = ["name" => $name, "count" => ""];
        }

        // 下单
        if (0 != $formData['order_state']) {
            $name = "";
            if (1 == $formData['order_time_type']) {    // 指定近几天
                if (!empty(is_numeric($formData['order_near_days']))) {
                    $name .= "近{$formData['order_near_days']}天 ";
                }
            } else {
                if (!empty($formData['order_start_time'])) {
                    $name .= "{$formData['order_start_time']}";
                }
                if (!empty($formData['order_end_time'])) {
                    $name .= "~{$formData['order_end_time']} ";
                }
            }

            if (1 == $formData['order_state']) {
                $name .= "从未下单";
            } else {
                $name .= "下单";
            }

            if (!empty($formData['order_frequency']) && key_exists($formData['order_frequency'], $freqNameArr)) {
                $name .= " {$freqNameArr[$formData['order_frequency']]} ";
            }
            //$orderCount = $userGroupModel->getCount($siteName, 0, [], [], $data['order_con'], []);
            $item[] = ["name" => $name, "count" => ""];
        }


        if (0 != $formData['mail_state']){
            $name = "";
            if (1 == $formData['mail_time_type']) {
                if (!empty(is_numeric($formData['mail_near_days']))) {
                    $name .= "近{$formData['mail_near_days']}天 ";
                }
            } else {
                if (!empty($formData['mail_start_time'])) {
                    $name .= "{$formData['mail_start_time']}";
                }
                if (!empty($formData['mail_end_time'])) {
                    $name .= "~{$formData['mail_end_time']} ";
                }
            }
            $mailStateArr = [1 => "从未发送", 3 => "已发送", 2 => "发送未打开", 4 => "邮件打开", 5 => "打开未点击", 6 => "打开并点击"];
            if (key_exists($formData['mail_state'], $mailStateArr)) {
                $name .= " " . $mailStateArr[$formData['mail_state']];
            }
            if (!empty($formData['mail_open_frequency']) && key_exists($formData['mail_open_frequency'], $freqNameArr)) {
                $name .= " 且打开次数{$freqNameArr[$formData['mail_open_frequency']]} ";
            }
            if (!empty($formData['mail_click_frequency']) && key_exists($formData['mail_click_frequency'], $freqNameArr)) {
                $name .= " 且点击次数{$freqNameArr[$formData['mail_click_frequency']]} ";
            }
            //$mailCount = $userGroupModel->getCount($siteName, 0, [], [], [], $data['mail_con']);
            $item[] = ["name" => $name, "count" => ""];

        }
        
        // 品类相关
        $category = new Category();
        $selectNameArr = [];
        $selectNameStr = "";
        
        // 单分类
        if (!empty($formData['relation']) && !empty($formData['category_id']) && is_array($formData['category_id'])) {
            foreach ($formData['category_id'] as $categoryId) {
                if (!empty($categoryId)) {
                    $selectNameTmp = $category->getCateNameById($categoryId,$formData['site_id']);
                    if (!empty($selectNameTmp)) {
                        $selectNameArr[] = $selectNameTmp;
                    }
                }
            }
            
            
            if ($formData['relation'] == 1) {
                $selectNameStr = join(' <font color="blue">and</font> ',$selectNameArr);
            } else {
                $selectNameStr = join(' <font color="blue">or</font> ',$selectNameArr);
            }
            
        }
        
        // 多级分类
        if (!empty($formData['relation']) && !empty($formData['category_id_info']) && is_array($formData['category_id_info'])) {
            $selectNameArr = [];
            $selectNameStr = "";
            $categoryIdArr = []; 
            $categoryTempStr = "";
            foreach ($formData['category_id_info'] as $categoryIdInfoVal) {
                if (!empty($categoryIdInfoVal)){
                   
                    $categoryTempId = 0;
                    
                    $categoryIdInfoValLen = count($categoryIdInfoVal);
                    $categoryTempId = $categoryIdInfoVal['category_id'.$categoryIdInfoValLen];
                   
                    if (!empty($categoryTempId)) {
                        $categoryIdArr[] = $categoryTempId;
                    }
                    // if (!empty($categoryTempStr)) {
                        // $selectNameArr[] = trim($categoryTempStr,"/");
                    // }
                }
            }
            if (!empty($categoryIdArr)) {
                $categoryIdArr = array_unique($categoryIdArr);
            }
            
            foreach ($categoryIdArr as $categoryIdVal) {
                $categoryTempStr = $category->getCateNameById($categoryIdVal,$formData['site_id']);
                if (!empty($categoryTempStr)) {
                    $selectNameArr[] = $categoryTempStr;
                }
            }
            if ($formData['relation'] == 1) {
                $selectNameStr = join(' <font color="blue">and</font> ',$selectNameArr);
            } else {
                $selectNameStr = join(' <font color="blue">or</font> ',$selectNameArr);
            }
        }
        
        if (!empty($selectNameStr)) {
            $item[] = ["name" => $selectNameStr, "count" => ""];
        }
        return $item;
    }

}
